【发布时间】:2016-08-17 16:31:51
【问题描述】:
我使用 redux-thunk 和 Axios 进行了异步调用。一切正常,但是我很难构建我的组件。我不知道如何映射我的道具/数据。以下是数据在我的商店中的存储方式:
我想访问第二个数据数组。我正在尝试这个:
const mapStateToProps = (state) => {
return {
isFetching: state.ThunkData.isFetching,
data: state.ThunkData.data.data,
error: state.ThunkData.error,
};
};
出现以下错误:Cannot read property 'data' of null。我需要将data: state.ThunkData.data.data 替换为data: state.ThunkData.data 才能使我的应用程序正常工作。
在我的组件中添加{console.log(this.props.data.data)} 还给我这个:
如何将我想要的数据传递到我的道具中,以便我可以执行以下操作:
<ul>
{ props.map((m, i) =>
<li key={i}>{m.authorname}</li>
)}
</ul>
如果需要这里是我的详细代码:
我的动作创建者:
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);
});
};
我的组件:
class asyncL extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchTest(this.props.thunkData)
}
render() {
if (this.props.isFetching) {
return <p>{console.log(this.props.isFetching)}</p>
}else if (this.props.error) {
return <div>ERROR {this.props.error}</div>
}else {
return <p>{console.log(this.props.data.data)}</p>
}
}
}
我的减速机:
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;
}
};
【问题讨论】:
标签: javascript arrays reactjs react-redux