我在这里有2个文件:App.js和reducer.js我尝试使用React&Redux创建onclick切换动作(例如:背景颜色更改)。谁能帮助我在此代码中的哪里进行切换操作? (我之前在mapDispatchToProps中进行了setTimeout操作,它可以正常工作,但不能进行切换操作。)看到代码:
App.js
import React, { Component } from "react";
import "./App.css";
import { connect } from "react-redux";
class App extends Component {
render() {
return (
<div>
<button
style={{
backgroundColor: this.props.backgroundColor
}}
>
hello
</button>
<button onClick={this.props.changeTheColor}>change</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
backgroundColor: state.backgroundColor
};
};
const mapDispatchToProps = dispatch => {
return {
changeTheColor: () => {
dispatch({ type: "CHANGE_COLOR" }); //I think something should change here but I have no idea how :(
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
和reducer.js
const initialState = {
backgroundColor: "red"
};
const reducer = (state = initialState, action) => {
const updatedState = { ...state };
if (action.type === "CHANGE_COLOR") {
updatedState.backgroundColor = "yellow"; // I added else/if operation there before and didn't worked :(
}
return updatedState;
};
export default reducer;
有人知道如何在此处进行切换操作吗?我想将按钮的红色背景色更改为黄色,然后切换回acton
像这样改变减速器:
const reducer = (state = initialState, action) => {
switch (action.type) {
case "CHANGE_COLOR" : {
return { ...state, backgroundColor : 'yellow' }
}
default:
return state
};
快速更改是将colors
存储为状态的一部分,并具有另一个用于切换的颜色状态索引。
// Reducer
const initialState = {
colors: ['red', 'yellow'],
colorIndex: 0 // color state index to toggle
};
const reducer = (state = initialState, action) => {
if (action.type === "CHANGE_COLOR") {
return {
...state,
colorIndex: !state.colorIndex,
}
}
return state;
};
// In App.js
const mapStateToProps = state => {
const cid = state.colorIndex;
return {
backgroundColor: state.colors[cid]
};
};
从更广泛的角度来看,通常将颜色主题存储在上下文中(即ThemeContext
),并且组件可以具有内部状态以在不同的颜色主题之间进行切换(即亮模式与暗模式)。
您可以创建如下所示的减速器:
const initialState = {
backgroundColor: "yellow"
};
export default (state = initialState, action) => {
switch (action.type) {
case "CHANGE_COLOR":
return {
...state,
backgroundColor: red
};
default:
return state;
}
};