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 null

我正在对我的后端进行一个简单的 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);

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

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

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

const defaultState = {
   tools : []
}
const  myReducers = (state = defaultState,action)=>{
   //....other action
    default : 
     return state;
}