【问题标题】:Can I use dispatch without binding?我可以在没有绑定的情况下使用调度吗?
【发布时间】:2020-04-16 01:09:50
【问题描述】:

我有这个代码:

动作有效,数据正确返回。

import axios from 'axios'

export function getBooks(
    limit = 10,
    start = 0,
    order = 'asc'
) {
    const req = axios.get(`/api/books?limit=${limit}&skip=${start}&order=${order}`)
                .then(res => res.data);

    return {
        type: 'GET_BOOKS',
        payload: req
    }

}

在下一个文件中this.props为空

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getBooks } from '../actions'


class HomeContainer extends Component {

    constructor(props) {
        super(props);
        this.props.dispatch(getBooks(3, 0, 'desc'));
    }

    render() {
        console.log(this.props);    
        return (
            <div>
                Home Items
            </div>
        )
    }
}

function mapStateToProps(state) {
    return {
        book_reducer: state.book_reducer
    }
}

export default connect(mapStateToProps)(HomeContainer)

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import ReduxThunk from 'redux-thunk';

import reducers from './reducers';
import Routes from './routes';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
        <BrowserRouter>
            <Routes/>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));

book_reducer.js

export default function(state = {}, action) {
    switch(action.type) {
        case 'Get_BOOKS':
            return {...state, list:action.payload}
        default: return state;
    }
}

知道为什么这不起作用吗?

【问题讨论】:

  • 不要从构造函数分派,从componentDidMount分派,这将是更正确的方法。你可以只引用你拥有的props(又名删除this,然后调用props.dispatch(...)
  • 您没有在请求中使用async/await,您确定数据返回正确吗?
  • 还是空的book_reducer

标签: reactjs redux react-redux


【解决方案1】:

你在reducer中打错了

case 'Get_BOOKS':

应该是

case 'GET_BOOKS':这是你从函数返回的内容

【讨论】:

  • 已经在使用redux-thunkprops.book_reducer 为空
  • 如果 console.log(req) 返回一些东西,这里的一切看起来都很好。你需要分享你的减速器。顺便说一句,你是在我回答之后添加了 index.js 还是我看不到 redux-thunk 的盲人
  • console.log(req) 返回数据。我在您回答后添加了索引。添加了减速器代码。
  • book_reducer.js 你共享了 getBooks 函数
  • 你刚刚在 reducer 中打错了:case 'Get_BOOKS': GET_BOOKS
猜你喜欢
  • 2018-05-22
  • 1970-01-01
  • 2014-02-16
  • 2020-12-14
  • 1970-01-01
  • 2017-12-31
  • 2019-01-31
  • 2016-08-11
  • 2021-08-10
相关资源
最近更新 更多