Reactjs 如何更新旧的生命周期方法&x27;组件将接收道具';?
我得到了这个密码:Reactjs 如何更新旧的生命周期方法&x27;组件将接收道具';?,reactjs,Reactjs,我得到了这个密码: const mapStateToProps = (state) => { return { currentUser: state.mainstate.currentUser, appLoaded: state.mainstate.appLoaded, redirectTo: state.mainstate.redirectTo }}; const mapDispatchToProps = dispatch
const mapStateToProps = (state) => {
return {
currentUser: state.mainstate.currentUser,
appLoaded: state.mainstate.appLoaded,
redirectTo: state.mainstate.redirectTo
}};
const mapDispatchToProps = dispatch => ({
onLoad: (payload, token) =>
dispatch({ type: APP_LOAD, payload, token, skipTracking: true }),
onRedirect: () =>
dispatch({ type: REDIRECT })
});
class App extends React.Component {
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.redirectTo) {
store.dispatch( push(nextProps.redirectTo) );
this.props.onRedirect();
}
}
//...
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
componentDidUpdate(prevProps, prevState) {
if(this.props.redirectTo) {
store.dispatch( push(prevProps.redirectTo) );
this.props.onRedirect();
}
}
需要将其更新为新方法“getDerivedStateFromProps”,尝试如下操作:
static getDerivedStateFromProps(props, state) {
if (props.redirectTo) {
store.dispatch( push(props.redirectTo) );
props.onRedirect();
}
}
但我得到错误“初始状态未定义”。
如何将状态传递给getDerivedStateFromProps?
或者我应该使用“componentDidUpdate”
已尝试此代码:
const mapStateToProps = (state) => {
return {
currentUser: state.mainstate.currentUser,
appLoaded: state.mainstate.appLoaded,
redirectTo: state.mainstate.redirectTo
}};
const mapDispatchToProps = dispatch => ({
onLoad: (payload, token) =>
dispatch({ type: APP_LOAD, payload, token, skipTracking: true }),
onRedirect: () =>
dispatch({ type: REDIRECT })
});
class App extends React.Component {
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.redirectTo) {
store.dispatch( push(nextProps.redirectTo) );
this.props.onRedirect();
}
}
//...
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
componentDidUpdate(prevProps, prevState) {
if(this.props.redirectTo) {
store.dispatch( push(prevProps.redirectTo) );
this.props.onRedirect();
}
}
但也有错误