如何在调度操作后更新组件的本地状态?
就我而言,我会根据组件本地状态显示一个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存储中(使用mapStateToPros)
感谢。
答案 0 :(得分:1)
最后,我添加了一个新的reducer&#34; popin&#34;管理开/关状态。
行动创作者:
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 }
)
答案 1 :(得分:0)
您可以使用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)
请原谅我的拼写错误和括号。但想法是一样的