【问题标题】:I am not able to change state using set state in componentDidMount我无法使用 componentDidMount 中的设置状态更改状态
【发布时间】:2019-03-31 02:37:50
【问题描述】:

从 axios 获取请求得到响应后,我无法更改状态

这是一个使用 MERN 堆栈的简单登录/注册页面,只有在 node.js 后端授权他之后,我才尝试访问用户个性化页面。 我已经尝试了使用 _ismounted 常见的方法,但是经过一些调试后,我看到 componentWillMount 方法在 axios get 之后立即被调用,然后将 _isMounted 设置为 false,因此不会进入我使用 setState 的 if 代码中

class User extends Component {
    _isMounted = false;

    constructor(props){
        super(props)

        this.state={
            isAuthenticated:false
        }
    }

    componentDidMount(){
        this._isMounted = true;
        const token=localStorage.getItem("token");
        //alert(token);
        axios
        .get(`https://localhost:3443/users/${this.props.user}`,{ headers: { Authorization: `Bearer ${token}` } })
        .then(res => {
            if (this._isMounted){
            this.setState(() => ({
                isAuthenticated:true
              }));
            }
        })
        .catch(err => alert(JSON.stringify(err)));
    }
    componentWillUnmount() {
        this._isMounted = false;
      }

    render() {
        if(this.state.isAuthenticated===false) return(<Redirect to="/home" />)
        return(
            <div>
                Hello {this.props.user}
            </div>
        );
    }
}

我只想在页面呈现之前执行 axios get 以检查用户是否被授权并相应地更改状态。

【问题讨论】:

    标签: node.js reactjs axios


    【解决方案1】:

    您的代码从未到达componentDidMount 生命周期,因为在您的render 函数中,您正在检查isAuthenticated 是否为假并进行重定向。

    由于您将isAuthenticated 的初始值设置为false,它总是重定向到/home 并调用componentWillUnmount

    这是因为componentDidMount 在第一个render 完成之后运行。

    为了解决这个问题,您可以将isAuthenticated 的初始值设置为null,这样您的组件就会到达componentDidMount 并执行axios 调用来验证用户是否通过了身份验证。

    this.state = { isAuthenticated:null };
    

    【讨论】:

      【解决方案2】:

      像这样改变你的渲染功能..我认为它可能对你有帮助..

      render(){
           return (
           <div>
            {
                 this.state.isAuthenticated === false ? (
                            <Redirect to="/home" />
                 ):(
                            <div>{this.props.user}</div>
                    )
             }
            </div>
            )
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 2018-09-23
        相关资源
        最近更新 更多