如何在调度操作后更新组件的本地状态?
在我的例子中,我显示了一个基于组件本地状态的 popin :
<button onClick={() => this.setState({ popin: true })}>Open</button>
<Popin hidden={!this.state.popin}>
<form onSubmit={createItem})>
<div className="popin-heading">...</div>
<button onClick={() => this.setState({ popin: false })}>Close</button>
<button type="submit">Submit</button>
</form>
</Popin>
提交点击时,createItem 调度操作在 Saga 中捕获:
function* watchCreateItem() {
yield takeEvery('CREATE_ITEM', doCreateItem);
}
function* doCreateItem(values) {
try {
// Do POST API request
const response = yield fetch('/create', { method: 'post', body: values });
// Disptach action to store new item in redux store (by reducer)
yield put(storeItem(response));
/**
* !!! Here, want to update 'state.popin = null' !!!
*/
} catch (error) {
showNotification(reponse.message, 'error');
}
}
API post请求成功后如何关闭popin?
我想继续将 popin 状态存储在本地组件状态中,而不是存储在 Redux 存储中(使用 mapStateToPros)
谢谢。
最佳答案
最后,我添加了一个新的 reducer “popin”来管理打开/关闭状态。
Action 创建者:
function ShowPopinAction(current = 'default') {
return { action: 'POPIN_STATE', current};
}
function HidePopinAction() {
return ShowPopinAction(null);
}
reducer :
function (state = {current: null}, action) {
if (action.type === 'POPIN_STATE') {
return {current: action.current}
}
return state;
}
在我的组件中:
<button onClick={ () => ShowPopinAction('createItem') }>Open</button>
<Popin hidden={this.props.current !== 'createItem'}>
....
<button onClick={HidePopinAction}>Close</button>
</Popin>
connect(
state = > ({ current: state.popin.current }),
{ ShowPopinAction, HidePopinAction }
)
关于reactjs - Redux Saga - 更新本地状态的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098310/