所以我有 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 stylesclass 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)) }
1 回答
阿晨1998
TA贡献2037条经验 获得超6个赞
我认为 redux 无法识别状态更改,因为对 squareColors 数组的引用保持不变,因此您必须传递该数组的副本,该副本将具有对 setColors 方法的新引用。
updateSquaresColors = (color = null) => {
let squareColors = this.props.squareColors;
squareColors.unshift(color);
squareColors.pop();
this.props.setColors([...squareColors]); //changed
localStorage.setItem('lastTenColors', JSON.stringify(squareColors))
}
添加回答
举报
0/150
提交
取消