尽管更新了 redux 状态,但组件不会重新渲染

所以我有 4 个不同颜色的 4 个按钮和 10 个方块,它们应该具有最后 10 次点击按钮的颜色。


我映射到 redux 状态以显示正方形。我还将 squareColors 存储在localStorage.


当我点击一个按钮时,状态会更新,所以我应该立即看到方块颜色的变化。但是,它仅在我刷新页面时发生。App.js单击按钮时,我的组件不会重新渲染。


为什么 ?


应用程序.js:


import React from 'react';

import { connect } from 'react-redux';

import { setColors } from './redux/actions';

import './App.css';

import CornerButton from './components/CornerButton';

import Square from './components/Square';


const styles = // some styles


class App extends React.Component {


  componentDidMount() {

    if (localStorage.getItem('lastTenColors')) {

      let squareColors = JSON.parse(localStorage.getItem('lastTenColors'));

      this.props.setColors(squareColors);

    } else {

      let squareColors = localStorage.setItem('lastTenColors',  JSON.stringify([...Array(10)]));

      this.props.setColors(squareColors);

    }

  }


  render() {

    return (

          <div style={styles.container}>

            <div style={styles.topRow}>

              <CornerButton color="red"/>

              <CornerButton color="blue"/>

            </div>

            <div style={styles.middleRow}>

              {this.props.squareColors.map((color, i) => <Square key={i} color={color}/>)}

            </div>

            <div style={styles.bottomRow}>

              <CornerButton color="cyan"/>

              <CornerButton color="green"/>

            </div>

          </div>

      );

  }

}


const mapDispatchToProps = { setColors }


const mapStateToProps = state => {

  return {

    squareColors: state.colors.squareColors

  }

}


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

角按钮.js:


import React from 'react';

import { connect } from 'react-redux';

import {setColors} from '../redux/actions';


const styles = // some styles...


class CornerButton extends React.Component {


  updateSquaresColors = (color = null) => {

    let squareColors = this.props.squareColors;

    squareColors.unshift(color);

    squareColors.pop();

    this.props.setColors(squareColors);

    localStorage.setItem('lastTenColors',  JSON.stringify(squareColors))

  }


有只小跳蛙
浏览 257回答 1
1回答

阿晨1998

我认为 redux 无法识别状态更改,因为对 squareColors 数组的引用保持不变,因此您必须传递该数组的副本,该副本将具有对 setColors 方法的新引用。&nbsp; &nbsp; &nbsp; updateSquaresColors = (color = null) => {&nbsp; &nbsp; &nbsp; &nbsp; let squareColors = this.props.squareColors;&nbsp; &nbsp; &nbsp; &nbsp; squareColors.unshift(color);&nbsp; &nbsp; &nbsp; &nbsp; squareColors.pop();&nbsp; &nbsp; &nbsp; &nbsp; this.props.setColors([...squareColors]); //changed&nbsp; &nbsp; &nbsp; &nbsp; localStorage.setItem('lastTenColors',&nbsp; JSON.stringify(squareColors))&nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript