React redux - 父状态改变,但子组件不重新渲染

use*_*707 3 javascript reactjs redux

我只是想学习使用 redux,我有一个非常简单的计数器列表组件,它有一个子计数器组件的列表。

我在计数器上有一个 onIncrement 操作,我想在单击时增加计数。

当我单击增量时,它会更新父状态,但是子计数器不会更新。如果我浏览然后返回列表,它确实呈现正确,在我看来这意味着状态已更新。

这是我的代码:

计数器组件

import React, { Component } from "react";
import { connect } from 'react-redux';
import { incrementCounter } from '../../actions/counterActions';
import PropTypes from 'prop-types';

class Counter extends Component {
    render() {
        return <div className="m-2">
            <b>{this.props.counter.count}</b>
            <button className="btn btn btn-secondary btn-sm m-2" onClick={() => { this.onIncrement(this.props.counter) }}>Increment</button>
        </div>;
    }

    onIncrement(counter) {
        this.props.incrementCounter(counter);
    }
}

const mapStateToProps = state => ({
})

Counter.propTypes = {
    incrementCounter: PropTypes.func.isRequired,
}

export default connect(mapStateToProps, { incrementCounter })(Counter);
Run Code Online (Sandbox Code Playgroud)

计数器列表组件

import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { CounterContext } from "../../contexts/context.js";
import Counter from "./Counter";
import { NewItem } from "./NewItem";
import ItemContainer from "../layout/ItemContainer";

import { connect } from 'react-redux';
import { getCounters } from '../../actions/counterActions';
import PropTypes from 'prop-types';

class CounterList extends Component {
    componentWillMount() {
        if (this.props.counters.length == 0) {
            this.props.getCounters();
        }
    }

    render() {
        const counterItems = this.props.counters.map(counter => <Counter key={counter.id} counter={counter} />);
        return <div>{ counterItems }</div>;
    }
}

const mapStateToProps = state => ({
    counters: state.counters.items
})

CounterList.propTypes = {
    getCounters: PropTypes.func.isRequired,
    counters: PropTypes.array.isRequired
}

export default connect(mapStateToProps, { getCounters })(CounterList);
Run Code Online (Sandbox Code Playgroud)

反动作

import { GET_COUNTERS, INCREMENT_COUNTERS } from '../actions/types';

export const getCounters = () => dispatch => {
    const counters = [{ id: 1, count: 4 }, { id: 2, count: 3 }, { id: 3, count: 0 }];
    // this could be API call to get initial counters
    console.log('In GetCounters', GET_COUNTERS);

    return dispatch({
        type: GET_COUNTERS,
        payload: counters
    })
}

export const incrementCounter = (counter) => dispatch => {
    // this could be API call to get initial counters
    counter.count++;

    return dispatch({
        type: INCREMENT_COUNTERS,
        payload: counter
    })
}
Run Code Online (Sandbox Code Playgroud)

计数器减速器

import { GET_COUNTERS, INCREMENT_COUNTERS } from '../actions/types';

const initialState = {
    items: []
}

export default function (state = initialState, action) {
    console.log(action.type);
    switch (action.type){
        case GET_COUNTERS:
            return {
                ...state,
                items: action.payload
            };
        case INCREMENT_COUNTERS:
            var counter = action.payload;

            const counters = [...state.items];
            const index = counters.findIndex(x => x.id == counter.id);
            counters[index] = counter;

            return {
                ...state,
                items: counters
            };
        default: 
            return state;
    }
}
Run Code Online (Sandbox Code Playgroud)

Swa*_*and 5

我想问题可能是您将具有更新的 count 值的相同旧计数器对象分配给您的 counters[index] ,因此 Counter 组件没有看到更改。这可能是因为 shouldComponentUpdate 进行了浅层检查,并且对 counter prop 的对象引用保持不变,并且您的组件不会重新渲染。

如果您在状态中使用多维数组或嵌套对象,则应该使用深度克隆。

推荐使用像 Immutable.js 这样的库来确保你的 reducer 保持纯净。

case INCREMENT_COUNTERS:
  var counter = action.payload;

  const counters = JSON.parse(JSON.stringify(state.items)); //this creates a deep copy
  const index = counters.findIndex(x => x.id == counter.id);
  counters[index].count = counter.count;

  return {
    ...state,
    items: counters
  };
Run Code Online (Sandbox Code Playgroud)