发送动作后如何更新组件的本地状态?
在我的例子中,我展示了一个基于组件本地状态的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>
在提交点击,Saga中的createItem dispatch action catch:
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发布请求成功后关闭popin?
我想继续将popin状态存储在本地组件状态而不是Redux存储中(使用mapStateToProps)
谢谢。
最后,我添加了一个新的reducer“popin”来管理打开/关闭状态。
行动创造者:
function ShowPopinAction(current = 'default') {
return { action: 'POPIN_STATE', current};
}
function HidePopinAction() {
return ShowPopinAction(null);
}
减速机:
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 }
)
您可以使用redux状态并使用mapStateToProps将其映射到组件。在组件中,不断更改componentWillReceiveProps生命周期中的状态。
component A extends React.Component {
this.state = {
isShowPopin: false
}
componentWillReceiveProps(nextProps) {
this.setState({isShowPopin: nextProps.isFetchedItem})
}
}
const mapStateToProps = (state) => {
return {
isFetchedItem : state.yourReducer.isFetched,
}
}
function mapDispatchtoProps() {
return {
//your dispatch to actions
}
}
connect(mapStateToProps, mapDispatchToProps)(A)
请原谅我的拼写错误和括号。但想法是一样的