我正在从组件分派(dispatch)一个操作,所有内容看起来都已正确链接,但是当我 console.log 组件 Prop 中的状态时,它尚未更新。
我尝试重新格式化我的代码并查看了多个示例,看起来它应该运行?当我从 reducer 登录时,它正在接收操作,但它只是不更新状态。
const mapStateToProps = state => ({
todos: state
});
onSubmit(e) {
e.preventDefault();
let payload = this.state.content
this.props.dispatch(post_todo(payload));
console.log(this.props.todos)
this.setState({
content: ""
})
}
export default (
state = [],
action
) => {
switch (action.type) {
case POST_TODO:
console.log("got it")
console.log(action.payload)
console.log(state)
return [
...state,
action.payload
];
default:
return state;
}
};
export function post_todo (payload){
return {
type: POST_TODO,
payload
};
}
它应该将 props.todos 更新到正确的状态,但每次都显示一个空数组。
最佳答案
onSubmit(e) {
e.preventDefault();
let payload = this.state.content
this.props.dispatch(post_todo(payload)); <=== this line
console.log(this.props.todos)
this.setState({
content: ""
})
}
当您在我指向的行发送操作时,它将执行您的操作,然后您可以在诸如 componentWillReceiveProps
之类的事件中接收新更新的 Prop ...
接收新的 props
到您的组件将导致您的组件重新渲染
因此,控制台在执行操作后立即记录您的 Prop ,永远不会为您提供新状态
...在componentWillReceiveProps
中等待它> 或 render
方法
以下是如何在您的案例中获取新 Prop (todos)的示例:
componentWillReceiveProps(nextProps) {
const { todos } = nextProps;
console.log('I recieved new todos', todos);
}
此外,如果您的 render
方法渲染任何显示您从 this.props.todos
获取的 todos
字段的组件...也会自动更新...
关于javascript - 操作调度不更新 Redux/React 中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327256/