使用 Redux-thunk 处理异步操作的组件结构?

Component structure to handle Async Action with Redux-thunk ?

经过一些尝试和错误,我终于设法让我的 action creator 正常工作并将我想要的数据传递到我的 redux 存储中。到目前为止,我一直在像这样 store.dispatch(fetchTest()); 发送它 "manually",但如果可以将这些数据用于一个组件,那就太好了。

这是我的动作创作者:

export const fetchTest = () => (dispatch) => {
    dispatch({
        type: 'FETCH_DATA_REQUEST',
        isFetching:true,
        error:null
  });
  return axios.get('http://localhost:3000/authors')
    .then(data => {
      dispatch({
            type: 'FETCH_DATA_SUCCESS',
            isFetching:false,
            data: data
      });
    })
    .catch(err => {
      dispatch({
            ype: 'FETCH_DATA_FAILURE',
            isFetching:false,
            error:err
      });
      console.error("Failure: ", err);
    });
};

这是我的减速器:

const initialState = {data:null,isFetching: false,error:null};
export const ThunkData = (state = initialState, action)=>{
    switch (action.type) {
        case 'FETCH_DATA_REQUEST':
        case 'FETCH_DATA_FAILURE':
        return { ...state, isFetching: action.isFetching, error: action.error };

        case 'FETCH_DATA_SUCCESS':
        return Object.assign({}, state, {data: action.data, isFetching: action.isFetching,
                 error: null });
        default:return state;

    }
};

到目前为止,使用 store.dispatch(fetchTest()); 时一切正常。

基于此 example 我尝试构建以下组件:

class asyncL extends React.Component {
                      constructor(props) {
                        super(props);
                      }
                      componentWillMount() {
                      this.props.fetchTest(this.props.thunkData)
                      // got an error here : "fetchTest is not a function"
                      }
                      render() {
                      if (this.props.isFetching) {
                            return console.log("fetching!")
        }else if (this.props.error) {
            return <div>ERROR {this.props.error}</div>
        }else {
            return <p>{ this.props.data }</p> 
        }
    }
}

            const mapStateToProps = (state) => {
                return {
                    isFetching: state.ThunkData.isFetching,
                    data: state.ThunkData.data.data,
                    error: state.ThunkData.error,
                };
            };


            const AsyncList = connect(mapStateToProps)(asyncL);
            export default AsyncList

它不起作用,我在 componentWillMount() 上有错误,可能在其他地方也有错误。

我的数据结构也有点奇怪。要真正访问数据数组,我必须执行 state.ThunkData.data.data。第一个数据对象充满了无用的东西,例如 requestheaders 等...

那么我应该如何编写这个组件,这样我至少可以将异步数据传递到 console.log。

谢谢。

你也需要mapDispatchToProps

import { fetchTest } from './myFetchActionFileHere';
import { bindActionCreators } from 'redux';

function mapDispatchToProps(dispatch) {
  return {
    fetchTest: bindActionCreators(fetchTest, dispatch)
  };
}

const AsyncList = connect(mapStateToProps, mapDispatchToProps)(asyncL);
export default AsyncList

文档 link:http://redux.js.org/docs/api/bindActionCreators.html