道具已更改,但未调用ComponentDidUpdate

时间:2020-06-23 17:33:33

标签: reactjs

我有一个警报/消息系统,该系统利用redux触发要呈现的警报组件。但是,我遇到了道具已更改但componentDidUpdate方法未运行的问题。这是我的代码:

App.js

const alertOptions = {
  timeout: 4000,
  position: 'top center',
  offset: '10px',
};

const AlertTemplate = ({ style, options, message }) => (
  <Alert
  style= {style}
  message={options.type}
  description={message}
  type={options.type}
  showIcon
  closable
/>)


class App extends Component {
  
  componentDidMount() {
    this.props.autoCheckState();
    }

  render() {    
    if (this.props.loading['authentication'] === true) {
        return <Spin size="large" />
    } else {
        return (
          <AlertProvider template={AlertTemplate}{...alertOptions}>
          <Router>
            <Alerts/>
            <Switch>
                <PrivateRoute exact path="/" component={Main}/>
                <Route path="/login" component={Login}/>
            </Switch>
          </Router>
          </AlertProvider>
        )

      }
  }
}
  
const mapDispatchToProps = dispatch => {
  return {
    autoCheckState: () => dispatch({ type: 'CHECK_AUTH'})
  }
}
const mapStateToProps = state => ({
  loading: state.loading.loading,
});


    
export default connect(mapStateToProps,mapDispatchToProps)(App);

Alert.js(组件)

class Alerts extends Component {
  componentDidUpdate(prevProps) {
    console.log('HELOOOOOOOO') //<--- Log to see if this life cycle method is running
    const { error, alert, message } = this.props;
    if (error !== prevProps.error && error) {
      if (error.detail) {
        if (error.detail === "Given token not valid for any token type") {
          alert.error('Your session has ended , please reverify your credentials')
        } else {
          alert.error(error.detail)
        }
      }
      if (error.name) alert.error(error.name);
      if (error.email) alert.error(error.email);
      if (error.message) alert.error(error.message);
      if (error.new_password) alert.error(error.new_password);
      if (error.old_password) alert.error(error.old_password);
      if (error.non_field_errors) alert.error(error.non_field_errors);
      if (error.username) alert.error(error.username);
      if (error.custom) alert.error(error.custom);
    }
    if (message !== prevProps.message  && message) {
      alert.success(message)
    }
  }

  render() {
    console.log(this.props.error)   //<---- log to show that the props have changed.
    return <Fragment />;
  }
}

const mapStateToProps = (state) => ({
  error: state.messages.error,
  message: state.messages.message,
});

export default connect(mapStateToProps)(withAlert()(Alerts));

为复制问题,我故意在login页面上输入了错误的用户凭据。 alert.js组件将记录以下内容:

输入任何凭据之前

null

键入错误的凭据后

{detail: "No active account found with the given credentials"}

0 个答案:

没有答案