React / Redux存储更新但Component不重新渲染

时间:2018-05-05 09:47:23

标签: reactjs typescript redux

我已经看到了很多关于这个标题的SO / github问题,我确信99%的情况下实际上没有做到导致此错误的原因: -connect包装器组件与MapStateToProps和MapDispatchToProps, - 返回新状态,而不是在reducer中改变实际状态。

在redux devtools扩展中,当我发送ADD_TODO时,我可以看到StoreState在列表中用新的Todo改变。当我调度ADD_TODO时,不会重新渲染Body组件。 如果我在todos初始StoreState中注入Todo,Todo将显示在Body Component中。

您可以找到存储库here

reducer:

import { TodoAction } from '../actions';
import { StoreState } from '../types/index';
import { ADD_TODO, TOGGLE_TODO } from '../constants/index';
import TodoModel from '../models/TodoModel';

export function todos(state: StoreState, action: TodoAction): StoreState {
    let todos: Array<TodoModel>;
    switch (action.type) {
        case ADD_TODO:
            todos = state.todos;
            todos.unshift(action.todo);
            return { ...state, todos: todos };
        case TOGGLE_TODO:
            todos = state.todos;
            const todo = todos.find(todo => todo.id === action.todo.id);
            if (todo !== undefined) {
                const key = todos.indexOf(todo);
                todos[key].done = true;
            }
            return { ...state, todos: todos };
        default:
            return state;
    }
}

容器组件:

export default connect(mapStateToProps, mapDispatchToProps)(Body);
import Body from '../components/Body/Body';
import { StoreState } from '../types/index';
import { connect } from 'react-redux';

export function mapStateToProps({ todos }: StoreState) {
    return {
        todos
    };
}

export function mapDispatchToProps() {
    return {
        //
    };
}
export default connect(mapStateToProps, mapDispatchToProps)(Body);

storeState更改未更新的组件:

import * as React from 'react';
import TodoModel from '../../models/TodoModel';

interface Props {
    todos: Array<TodoModel>;
}

interface State {

}

class Body extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
    }

    render() {
        console.log(this.props);
        return (
            <div>
                <ul>
                    {this.props.todos.map(todo => <li key={todo.id}>{todo.content}</li>)}
                </ul>
            </div>
        );
    }
}

export default Body;

1 个答案:

答案 0 :(得分:3)

unshift改变数组,你需要返回一个新数组:

case ADD_TODO:
    todos = [...state.todos]; // or - state.todos.slice();
    todos.unshift(action.todo);
    return { ...state, todos: todos };