ReactJS:类型错误:无法读取未定义的属性 'from'

标签 reactjs react-redux

当用户尝试重定向到我从 props.location 发送的私有(private)路由时,以便在登录后用户重定向回同一链接。

但是当用户直接登录页面时,它会显示

私有(private)路线

<Redirect to={{ pathname: '/sign-in', state: { from: props.location} }} />

登录页面:

componentWillReceiveProps(nextProps) {
    if (nextProps.apiData !== this.props.apiData && nextProps.apiData !== false) {
      if(!(this.props.location.state.from.pathname)) {
       this.props.history.push(this.props.location.state.from.pathname)
      }
      else{
        if (this.props.location.length === 0) {
          this.props.history.push("/");
        }
        else{
          this.props.history.goBack();
        }
      }
    }
  }

它给了我这个错误

类型错误:无法读取未定义的“来自”属性

最佳答案

this.props.location.state 仅当组件通过 Redirect 挂载时才存在,因此在访问它之前需要先检查它是否存在:

if (this.props.location.state && !this.props.location.state.from.pathname) {

关于ReactJS:类型错误:无法读取未定义的属性 'from',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169632/

相关文章:

javascript - componentWillReceiveProps 包含多个 if

reactjs - 在 React ES6 类中调用方法

javascript - Lodash 'get' 在箭头函数(React)中使用时不起作用

javascript - React-native 在浏览器中打开链接并返回应用

reactjs - 使用透明框架使 react Electron 应用程序可拖动

reactjs - 如何用redux组织 "sub-applications"?

reactjs - 如何在react类表单组件中检索当前的redux-form状态字段值?

react-native - 在 react-navigation 中使用 react-redux connect 方法显示错误 "The component for route ' x' must be a React component

node.js - 从 Nodejs 传递错误但未收到正确的错误

javascript - 为什么我的 "mapDispatchToProps"找不到我的 Action 函数?