反应-在render()期间“ this”变得不确定

时间:2019-10-26 12:41:04

标签: javascript reactjs react-router

所以我有一个基本的index.js页面,其中包含包裹在BrowserRouter中的应用程序,如下所示:

ReactDOM.render(
    <Router>
        <App/>
    </Router>,
    document.getElementById('root')
);

在App.js中,我有一个条件渲染来处理登录:

if(!this.state.loggedIn) return (
      <Container className="pt-5">
        <Login from={this.props.location}/>
      </Container>
    )
    else return (
      <div>
        <Menu/>
        <Container className="pt-5">
          <Switch>
            <Route path="/stuff" component={Stuff}/>
            <Route path="/morestuff" component={MoreStuff}/>
          </Switch>
        </Container>
      </div>
    )

在我的Login.js中,我有一个带有按钮的简单表单,该按钮触发箭头功能以验证登录。在箭头函数的末尾,它将调用 this.setState(),从而触发重新渲染。渲染功能如下:

render() {
    if (this.state.loggedIn) {
        const { from } = this.props.location.state || { from: { pathname: "/" } };
        return <Redirect to={from}/>
    }
    else return (
        <Container fluid>
            <input type="text"/>
            <input type="password"/>
            <Button onClick={this.authenticate}>Submit</Button>
        </Container>
    )
}

那么我的问题是:为什么我收到“ TypeError:无法读取未定义的属性'state'的未定义状态”?

if (this.state.loggedIn)

我觉得有些事情发生了故障。在我看来,这似乎很合乎逻辑:Login控件是在App.js中呈现的,用户按下了登录按钮,该按钮更改了Login的状态,从而导致其使用Redirect进行重新呈现,从而导致浏览器导航和App.js。重新加载新内容。我想念什么?

1 个答案:

答案 0 :(得分:0)

这不是访问this.state的错误,而是访问this.props.location.state的错误。

您没有将location道具传递给Login<Login from={this.props.location}/>),因此,当您尝试在this.props.location.state内部访问Login时,会收到错误消息:

const { from } = this.props.location.state <== || { from: { pathname: "/" } };

您需要执行以下操作:

<Container className="pt-5">
  <Login location={this.props.location}/>
</Container>