【问题标题】:List not rendering to parent component列表未呈现给父组件
【发布时间】:2018-03-27 08:14:54
【问题描述】:

我正在使用 react+redux 构建一个 Todo 应用程序。当我在列表中添加新的待办事项时,存储状态和 TodoList 组件的状态已成功更新,但我的 todoList 代码无法正常工作。 React 组件没有渲染列表。

状态结构如下。

State = [
   {
     id,
     text,
     completed
   },...
]

我的代码如下。

Todo.js

import React, { Component } from 'react';
import Form from './Form';
import TodoList from './TodoList';
import Filter from './Filter';

class ToDo extends Component {
    render() {
        return (
            <div>
                <h2>Todo App</h2>
                <Form />
                <TodoList />
                <Filter />
            </div>
        );
    }
}

export default ToDo;

TodoList.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toggleToDo } from '../actions';

class TodoList extends Component {
    constructor (props){
        super(props);
        this.state = {
            list: []
        };
    }

    render() {
        console.log(this);
        const todolist = this.state.list;
        return (
            <ul>
            {
                todolist.map(function(listValue) {
                    return <li>{listValue.text}</li>;
                })
            }
            </ul>
        );
    }
}

const mapStateToProps = (state) => {
    console.log('TodoList state',state);
    return {
        todos: state
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({toggleToDo},dispatch);
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

【问题讨论】:

  • 我没有看到您在 todolist 组件中使用道具中的 todos。对于要重新渲染的组件,它的状态应该更新
  • 为什么你试图以 TodoList 的状态存储数据。您已经在 redux 存储中拥有数据。其次,你应该有 const todolist = this.props.todos(从地图状态到道具的 todos)。

标签: reactjs


【解决方案1】:

您正在使用mapStateToProps 将您的状态映射到道具,因此您应该从道具中获取此状态值。

const { todos } = this.props; 并迭代 todos 而不是 todolist

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2014-08-12
    • 2013-06-08
    相关资源
    最近更新 更多