【问题标题】:Redux updates state (in reducers), but React components do not re-render?Redux 更新状态(在 reducer 中),但 React 组件不会重新渲染?
【发布时间】:2020-06-24 05:02:54
【问题描述】:

这很奇怪,因为在我的减速器中,我确保我没有改变状态;此特定问题的常见问题。但是,我仍然不断收到这个问题。在应用程序的初始加载(使用 npm start)。在下面的照片中,您可以看到我在 return 语句之前 console.log 每个组件作为测试以查看组件是否呈现。但是尽管状态被更新,组件永远不会重新渲染......(我相信容器设置正确并且组件被调用。)

AllGiftsDisplay

import OneGiftDisplay from './OneGiftDisplay.jsx';

const AllGiftsDisplay = (props) => {
  console.log("LOADING");
  let individualGifts = [];
  for(let i = 0; i < props.giftList.length; i++) {
    individualGifts.push(
      <OneGiftDisplay
        addGift = {props.addGift}
        updatedGiftMessage = {props.updateGiftMessage}
        setNewMessage = {props.setNewMessage} 
        totalVotes = {props.totalVotes}
      />
    )
  }  
  // let list = [<OneGiftDisplay/>, <OneGiftDisplay/>]
  return (
    <div className = "displayAllGifts">

      {/* {console.log("~~~giftlist length", props.giftList.length)} */}
      {individualGifts} 
      {/* {list} */}
    </div>
  )
};

export default AllGiftsDisplay;

礼品减少器

import * as types from '../constants/actionTypes.js';

const initialState = {
    giftList: [],
    lastGiftId: 10000,
    totalVotes: 0,
    newMessage: ''
};

const giftReducer = (state=initialState, action) => {
  // let giftList;
  // let setMessage;

  switch(action.type) {
    case types.ADD_GIFT:
      let stateCopy = { ...state }; // shallow copy

      // create the new gift object structure.
      const giftStructure = {
        // lastGiftId: stateCopy.lastGiftId,
        newMessage: stateCopy.newMessage,
        totalVotes: 0
      };

      // push the new gift onto the list.
      stateCopy.giftList.push(giftStructure);
      // console.log("giftList: ", stateCopy.giftList);s
      // return updated state
      return {
        ...stateCopy,
        newMessage: ''
      }

    case types.SET_MESSAGE:
      return {
        ...state, newMessage: action.payload,
      }

    case types.ADD_VOTE:

    case types.DELETE_GIFT:

    default:
      return state;
  }
};

export default giftReducer;

列表容器

import React, { Component } from 'react';
import { connect } from 'react-redux';

// import actions from action creators file
import * as actions from '../Actions/actions';
import AllGiftsDisplay from '../Components/AllGiftsDisplay.jsx';
import GiftCreator from '../Components/GiftCreator';

const mapStateToProps = (state) => ({
    lastGiftId: state.gifts.lastGiftId,
    giftList : state.gifts.giftList,
    totalVotes: state.gifts.totalVotes,
    setNewMessage: state.gifts.setNewMessage
});

//pass in text into update
const mapDispatchToProps =  dispatch => ({
    updateGiftMessage: (e) => { 
        console.log(e.target.value);
        dispatch(actions.setMessage(e.target.value));
    },
    addGift: (e) => {
        e.preventDefault();
        console.log("actions: ", actions.addGift);
        dispatch(actions.addGift());
    }
});
  
  class ListContainer extends Component {
    constructor(props) {
      super(props);
    }
  
    render() {
      return(
        <div className="All-Lists">
            <h1>LIST CONTAINER!</h1>
                <AllGiftsDisplay giftList = {this.props.giftList} addGift={this.props.addGift} setNewMessage={this.props.setNewMessage} totalVotes = {this.props.totalVotes} lastGiftId = {this.props.lastGiftId}/>
                <GiftCreator setNewMessage={this.props.setNewMessage} updateGiftMessage={this.props.updateGiftMessage} addGift={this.props.addGift}/>
        </div>
      );
    }
  }
  
  export default connect(mapStateToProps, mapDispatchToProps)(ListContainer);

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    秘诀是避免变异giftList

    const giftReducer = (state=initialState, action) => {
      // let giftList;
      // let setMessage;
    
      switch(action.type) {
        case types.ADD_GIFT:
    
          // create the new gift object structure.
          const giftStructure = {
            // lastGiftId: stateCopy.lastGiftId,
            newMessage: stateCopy.newMessage,
            totalVotes: 0
          };
    
          return {
            ...state,
            giftList: [...state.giftList, giftStructure],
            newMessage: ''
          }
    
        case types.SET_MESSAGE:
          return {
            ...state, newMessage: action.payload,
          }
    
        case types.ADD_VOTE:
    
        case types.DELETE_GIFT:
    
        default:
          return state;
      }
    };
    

    为了更好地理解为什么不必改变数组,请考虑以下示例:

    const arr = [1, 2, 3];
    const b = { a: arr };
    const c = { ...b };
    c.a.push(4);
    console.log(arr === c.a); // outputs true
    

    【讨论】:

    • 我仍然遇到同样的错误:/。它不会重新渲染组件,但会在技术上更新状态。
    • 出于好奇,能否尝试在ListContainerrender() 方法中做console.log(this.props.giftList),然后尝试添加礼物?添加后能看到新的控制台消息吗?
    • 等一下,它确实有效!我只需要重新启动我的构建。很抱歉,非常感谢你:)
    • 别担心,喜欢你的昵称:)
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多