所以我有 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))
}
阿晨1998
相关分类