【发布时间】:2016-11-20 19:51:55
【问题描述】:
我是 redux 的新手,尝试调用 API 并将返回的用户对象数组传递给 state.admin.users。
我的代码: //组件
class MyComponent extends Component {
componentWillMount() {
console.log( 'componentWillMount()' );
this.props.fetchAllUsers();
}
render() {
return (
<div>
<ul>
{
this.props.users.map( function(user) {
return <div>user.email</div> })
}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
console.log( 'state:' + JSON.stringify(state) );
return {
users: state.admin.users
}
}
export default connect(mapStateToProps, {fetchAllUsers})(myComponent);
// 减速器
const INITIAL_STATE = { users:[] };
export default function (state = INITIAL_STATE, action) {
return { ...state, users:action.payload }; // Any problem here?
}
// 动作
export function fetchAllUsers() {
return function(dispatch) {
axios.get(`${API_URL}/users`)
.then(response => {
console.log( 'response.data:' +JSON.stringify(response.data) );
dispatch({
type: FETCH_ALL_USERS,
payload: response.data // Any problems here?
});
})
.catch(response => dispatch(errorHandler(response.data.error)))
}
}
控制台输出
state:{"admin":{}} bundle.js:2570:1
componentWillMount() bundle.js:295:8
选项 XHR http://myip:3001/api/users [HTTP/1.1 200 OK 2ms]
GET XHR http://myip:3001/api/users [HTTP/1.1 304 未修改 4ms]
response.data:[{数据已删除}{数据已删除}{数据已删除}]
response.data 对我来说看起来不错。但是上面的代码有什么问题吗?为什么 state.admin 是空的?为什么componentWillMount() 在mapStateToProps 之后调用?
欢迎任何 cmets。谢谢
【问题讨论】:
标签: javascript redux react-redux redux-thunk