与history.push一起使用重定向时无法更改状态

问题描述 投票:0回答:1

我有以下方法:

export const getPublication = async (id, props) => {
    const idJSON = {"id": id,}
    return await axios({
        method: 'post',
        url: 'users/getPublicationByID',
        data: idJSON
      })
      .then(function (response) {
          return response.data
      })
      .catch(function (error) {
          alert(error.response.status); // Works fine 
          props.history.push({
            pathname: '/error',
            state: { hasError: true, coding: error.response.status }
          })
      });
}

现在,此方法似乎很好用,因为当发现错误时,它将我从原先的页面重定向到'/ error'。但是,错误页面似乎没有更新其编码变量。

class ErrorBoundary extends React.Component {

    constructor(props) {
        super(props);
        this.state = { 
            hasError: false,
            coding: props.coding
        };
    }

    render(){
        const { t } = this.props;
            var codeMsg = t('errors.errorCode') + this.state.coding;
            alert(codeMsg); // says it's undefined!
            return ( 
                ...
            );     
    }

}

export default withTranslation()(ErrorBoundary);
reactjs
1个回答
2
投票

提供给路由组件的state可从location.state获得

coding: props.location.state.coding

docs

© www.soinside.com 2019 - 2024. All rights reserved.