如何更新旧的生命周期方法“ componentWillReceiveProps”?

时间:2020-09-24 19:24:23

标签: reactjs

我得到了以下代码:

doc.paragraphs[7].text = doc.paragraphs[7].text.replace('98%','85%')

需要尝试将其更新为新方法“ getDerivedStateFromProps”:

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);

但是出现错误“初始状态未定义”。 我应该如何将状态传递给getDerivedStateFromProps? 或者我应该使用'componentDidUpdate' 尝试了这段代码:

static getDerivedStateFromProps(props, state) {
  if (props.redirectTo) {
     store.dispatch( push(props.redirectTo) );
     props.onRedirect();
  }
}

但也出现错误

0 个答案:

没有答案