【问题标题】: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);

【问题讨论】:

  • 请添加减速器

标签: reactjs api redux redux-thunk


【解决方案1】:

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

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

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

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

【讨论】:

  • 非常感谢。我将减速器中的状态初始化为“null”,只是将其更改为“[]”。它仍然呈现两次,这是预期的行为吗?
  • yes.twice 表示 .第一次 。当你设置数据时存储初始化和第二次。你可以使用shouldComponentUpdate生命周期来避免不必要的渲染。
猜你喜欢
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多