Arg*_*gaz 5 ecmascript-6 reactjs redux redux-saga react-redux
如何在调度操作后更新组件的本地状态?
就我而言,我显示了一个基于组件本地状态的 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>
Run Code Online (Sandbox Code Playgroud)
在提交单击时,在 Saga 中 createItem 调度动作捕获:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
API post请求成功后如何关闭popin?
我想继续将 popin 状态存储在本地组件状态而不是 Redux 存储中(使用 mapStateToPros)
谢谢。
尝试以下使用 componentDidUpdate 和 mapStateToProps 的代码
class A extends React.Component {
state = {
isShowPopin: false
};
componentDidUpdate(prevProps, prevState) {
const { isFetchedItem: prevPropsisFetchedItem } = prevProps;
const { isFetchedItem } = this.props;
if (isFetchedItem !== prevPropsisFetchedItem) {
this.setState({ isShowPopin: isFetchedItem });
}
}
}
const mapStateToProps = state => {
return {
isFetchedItem: state.yourReducer.isFetched
};
};
function mapDispatchtoProps() {
return {
//your dispatch to actions
};
}
connect(mapStateToProps, mapDispatchToProps)(A);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4083 次 |
| 最近记录: |