【发布时间】:2019-06-03 12:23:52
【问题描述】:
所以我有 4 个 4 种不同颜色的按钮和 10 个正方形,它们应该具有最后 10 次单击按钮的颜色。
我在 redux 状态上映射以显示正方形。我还将 squareColors 存储在 localStorage 中。
当我点击一个按钮时,状态会更新,所以我应该立即看到方块颜色的变化。但是,它仅在我刷新页面时发生。当我单击按钮时,我的 App.js 组件不会重新呈现。
为什么?
App.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);
CornerButton.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))
}
render() {
return (
<button
style={{...styles.button, color: this.props.color, borderColor: this.props.color}}
onClick={() => this.updateSquaresColors(this.props.color)}>
click me!
</button>
);
}
}
const mapDispatchToProps = { setColors }
const mapStateToProps = state => {
return {
squareColors: state.colors.squareColors
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CornerButton);
Square.js:
import React from 'react';
const styles = //some styles...
const Square = props => (
<div style={{...styles.square, backgroundColor: props.color}}>
</div>
);
export default Square;
动作和减速器:
//action
import { SET_COLORS } from "./actionTypes";
export const setColors = (squareColors = [...Array(10)]) => ({
type: SET_COLORS,
payload: {
squareColors
}
});
// reducer
const initialState = {
squareColors: [...Array(10)]
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_COLORS: {
return {
...state,
squareColors: action.payload.squareColors
};
}
default:
return state;
}
}
【问题讨论】:
标签: javascript reactjs redux react-redux