React/Redux Tools.js:9 Uncaught TypeError: Cannot read property 'map' of null

Posted

技术标签:

【中文标题】React/Redux Tools.js:9 Uncaught TypeError: Cannot read property \'map\' of null【英文标题】:React/Redux Tools.js:9 Uncaught TypeError: Cannot read property 'map' of nullReact/Redux Tools.js:9 Uncaught TypeError: Cannot read property 'map' of null 【发布时间】:2018-07-22 05:12:17 【问题描述】:

我正在对我的后端进行简单的 api 调用以显示所有工具。我正在使用 Redux/Redux Thunk 来处理应用程序的状态。在我的 /tools 页面上,它应该只列出数据库中的所有工具。看起来它正在渲染两次,因为 props.tools 最初为空,然后具有工具数组。不幸的是,这仍然会导致错误。如果有人能解释这种行为以及如何解决它,我将不胜感激。

import React,  Component  from 'react';
import  connect  from 'react-redux';

class Tools extends Component 
  render() 
    console.log(this.props);
    console.log('tools', this.props.tools);

    const allTools = this.props.tools.map(tool => <li>tool</li>);

    return (
      <div>
        <h1>tools</h1>
        <ul>allTools</ul>
      </div>
    ) 
  


function mapStateToProps(state) 
  return  tools: state.tools ;


export default connect(mapStateToProps)(Tools);

【问题讨论】:

请添加减速器 【参考方案1】:

reducer 第一次初始化时,没有tools 的值 所以,你得到了tools=null,因此出现了一个错误。

您必须在减速器中将其设置为默认值。

在你的 reducer 中,只需要将 tools 初始化为默认值。

const defaultState = 
   tools : []

const  myReducers = (state = defaultState,action)=>
   //....other action
    default : 
     return state;

【讨论】:

非常感谢。我将减速器中的状态初始化为“null”,只是将其更改为“[]”。它仍然呈现两次,这是预期的行为吗? yes.twice 表示 .第一次 。当你设置数据时存储初始化和第二次。你可以使用shouldComponentUpdate生命周期来避免不必要的渲染。

以上是关于React/Redux Tools.js:9 Uncaught TypeError: Cannot read property 'map' of null的主要内容,如果未能解决你的问题,请参考以下文章

React+Redux学习笔记:React+Redux简易开发步骤

React之React-redux数据流转流程

React全家桶React-Redux

react+redux教程redux服务端渲染流程

react redux react-redux使用方式

react+redux+react-redux