首页 > 解决方案 > React.js:props.state 为空白(空)

问题描述

我想使用 React.js + Redux 的 Todo List。

我制作减速器文件:

import { ADD_POST, REMOVE_POST } from "../actions/index.jsx";

const initialState = {
 title: "",
 content: ""
};

export default function Post(state = initialState, action) {
 switch (action.type) {
  case ADD_POST:
   return [
    ...state,
    {
      id: action.id,
      title: action.title,
      content: action.content
    }
  ];
  case REMOVE_POST:
    return state.filter(({ id }) => id !== action.id);
  default:
    return state;
 }
}

而且,我编辑 App.js :

class App extends Component {
render() {
  return (
    <div className="App">
      <Input />
      <List posts={this.props.allPosts} />
  </div>
  );
 }
}

const mapStateToProps = state => {
 return {
   allPosts: [state.title, state.content]
 };
};

export default connect(mapStateToProps, null)(App);

而且,列表组件是...:

 render() {
   return (
     <div>
       <ul>
         {this.props.posts.map((post, index) => (
         <Item {...post} key={index} />
        ))}
       </ul>
     </div>
   );
  }
 }

我遇到错误“无法读取未定义的属性 'map'”并且无法继续。

我该如何解决?

我指的是多个来源,但我遇到了困难,因为我只能看到一个“文本”状态的文本,以及两个像“标题”和“内容”状态的来源。

- - - -_使固定

我修复了错误,但 props.state 为空白。我添加了带有文本的输入标签,但它并没有改变一切。

在此处输入图像描述

--------行动

export const ADD_POST = "ADD_POST";
export const REMOVE_POST = "REMOVE_POST";

let nextId = 0;

export function addPost(title, content) {
 return {
   type: ADD_POST,
   id: nextId++,
   title,
   content
 };
}

export function removePost(id) {
 return {
   type: REMOVE_POST,
   id
 };
}

标签: javascriptreactjsredux

解决方案


我认为您对您所在州的数据类型感到困惑。以下代码段可能对您有用。我将您的状态保留为一个帖子数组,其中 initialState 是一个空数组。
所以在你的 reducer 文件中,将 initialState 初始化为:

import {
  ADD_POST,
  REMOVE_POST
} from "../actions/index.jsx";

const initialState = [];

export default function Post(state = initialState, action) {
  switch (action.type) {
    case ADD_POST:
      return [
        ...state,
        {
          id: action.id,
          title: action.title,
          content: action.content
        }
      ];
    case REMOVE_POST:
      return state.filter(({
        id
      }) => id !== action.id);
    default:
      return state;
  }
}

在 App.js 中,在函数 mapStateToProps 中,将 allPosts 映射到数组状态。

class App extends Component {
render() {
  return (
    <div className="App">
      <Input />
      <List posts={this.props.allPosts} />
  </div>
  );
 }
}

const mapStateToProps = state => {
 return {
   allPosts: state
 };
};

export default connect(mapStateToProps, null)(App);


推荐阅读