我知道这个网站上有很多相同的问题,但没有一个与我的问题相关联。 这个 与我的问题接近,但我还没有使用数据库 。只是完整的
我正在为
当我第一次点击“添加任务”按钮时,即使从reducer中的日志显示为true,它也不会更新状态。第二次点击才能更新redux状态。我的任务CRUD在相同的redux设置下运作良好。我是否有什么误解?
react/redux
实现。我正在为
reactstrap
modal
中的示例项目实现redux,并且因为其中一个reducer在第一次更新状态时没有起作用而让我感到困惑。请考虑我的redux设置。
Action
export const showModal = (data) => {
return {
type: MODAL_TOOL,
payload: data
};
}
Reducer
const initialState = {
isOpen: false
};
export default function(state=initialState, action) {
switch(action.type) {
case MODAL_TOOL:
console.log(action.payload.isOpen); //logs true
return {
...state,
isOpen: action.payload.isOpen
}
default:
return state;
}
}
合并Reducer
export default combineReducers({
modal: modalReducer
});
组件
class TaskModel extends Component {
state = {
isOpen: this.props.modal.isOpen
}
onCreateTask = () => {
this.props.showModal({
isOpen: !this.props.modal.isOpen
});
this.setState({
isOpen: this.props.modal.isOpen
});
}
render() {
return(
<Button
size="sm"
color="dark"
style={{marginBottom: '2rem'}}
onClick={this.onCreateTask}
>
Add Task
</Button>
)
}
}
const mapStateToProps = (state) => ({
modal: state.modal
});
export default connect(mapStateToProps, { showModal })(TaskModel);
当我第一次点击“添加任务”按钮时,即使从reducer中的日志显示为true,它也不会更新状态。第二次点击才能更新redux状态。我的任务CRUD在相同的redux设置下运作良好。我是否有什么误解?
setState()
一样是异步的。因此,使用存储值this.props.modal.isOpen
的setState()
调用可能不会使用正确的值,因为您在调度操作后同步调用它。 - Jayce444mapStateToProps
和connect
需要放在类外面。 - FawazisOpen
保留在 redux 或状态中的一个位置即可,不要同时存在两个地方。 - Fawaz