【问题标题】:TypeError: Cannot read property 'searchField' of nullTypeError:无法读取 null 的属性“searchField”
【发布时间】:2019-03-22 17:06:39
【问题描述】:

TypeError:无法读取 null 的属性“searchField” App.render

【问题讨论】:

  • 你是如何定义state的?
  • 这是发生错误的新文件,如果是愚蠢的错误,请道歉:github.com/ahmedabdo97/robofriends/blob/master/src/containers/…
  • App.jsrender函数的return语句括在()中试试。有时会弄得一团糟。
  • 感谢修复似乎依赖于它的道具,所以我做了 this.props 而不是 this.state 并且它工作正常

标签: javascript reactjs react-redux


【解决方案1】:

TypeError:无法读取 null 的属性“searchField”

表示编译器未在您的组件中找到state

并且您想从redux 检索此值,因此您必须使用 this.props 而不是 this.state

【讨论】:

    【解决方案2】:

    正如我所见,您尝试使用的所有道具都来自商店(通过 mapStateToProps),所以不是

    const { searchField, onSearchChange, robots, isPending } = this.state;
    

    你应该这样做

    const { searchField, onSearchChange, robots, isPending } = this.props;
    

    另外,如果你在 render 中使用 state,别忘了在组件或构造函数中初始化 state:

    // if your state doesn't depend on props    
    class App extends Component {
             state = {
               isLoading: false
             }
        ....
    
    
    
    //if your state depends on props(rare case but sometimes useful)
    
    class App extends Component {
       constructor(props) {
          super(props);
    
          const {isLoading} = props;
          this.state = {
             isLoading
          }
        }
    ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 2022-01-12
      • 2021-12-04
      • 2021-12-17
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多