我是redux的新手,尝试调用API并将返回的User对象数组传递给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);
// reducer
const INITIAL_STATE = { users:[] };
export default function (state = INITIAL_STATE, action) {
return { ...state, users:action.payload }; // Any problem here?
}
// actions
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)))
}
}
控制台输出
陈述:{&#34; admin&#34;:{}} bundle.js:2570:1
componentWillMount()bundle.js:295:8
选项XHR http://myip:3001/api/users [HTTP / 1.1 200 OK 2ms]
获取XHR http://myip:3001/api/users [HTTP / 1.1 304未修改4ms]
response.data:[{data removed} {data removed} {data removed}]
response.data对我来说很好看。但上述代码中的任何问题?为什么state.admin是空的?为什么componentWillMount()
在mapStateToProps
之后调用?
欢迎任何评论。感谢
答案 0 :(得分:0)
你的减速机应该是这样的:
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_ALL_USERS:
return Object.assign({}, state, {
users: action.payload
});
}
return state;
}
此外,您的代码段不会显示您如何定义根减速器。它是否有admin
键指向此缩减器?