我有以下Codesandbox.io
:
https://codesandbox.io/s/qxkq5vvm1q
这是一个基本的 ReactJS/Redux
应用程序。
这里的关键组件是:
一个
Select
,它通过以下方式获取其值:Redux(状态管理器)->PanelMaterialSize(容器)->Select
一个
Updater
组件,负责通过Redux
更新Select
上可用的值Alert
按钮,单击该按钮时会提醒store
中存储的值
应该发生的是:
当用户更改
Select
上的选项时,该值应存储在商店中。这实际上是正确发生的 - 好的如果
Select
的值发生更改(例如,由于Updater
组件),那么它应该自动更改存储在存储中的值它正在显示(类似于用户更改其值)。不幸的是这并没有发生 - 目标
以下是一些代码:
./src/controls/Select/Select.js
import React, { Component } from "react";
import "./Select.scss";
class Select extends Component {
constructor(props) {
super(props);
let { name, data, className, ...controlProps } = this.props;
this.name = name;
this.data = data;
this.controlProps = controlProps;
this.state = {
[name]: data,
className
};
}
render() {
let data = this.state[this.name];
return (
<div className="control-select" {...this.controlProps}>
<div className="custom-dropdown custom-dropdown--grey">
<select className="custom-dropdown__select custom-dropdown__select--grey">
{this.props.data.length > 0 &&
this.props.data.map((elem, index) => {
return (
<option value={elem.value} key={index}>
{elem.text}
</option>
);
})}
</select>
</div>
</div>
);
}
}
export default Select;
src/controls/PanelMaterialSize/PanelMaterialSize.js
import React, { Component } from "react";
import { connect } from "react-redux";
import "./PanelMaterialSize.scss";
import Select from "../Select/Select";
import { setThemeList, setSelectedTheme } from "../../store/AppConfig/actions";
class PanelMaterialSize extends Component {
constructor(props) {
super(props);
this.state = {
selection: "",
options: []
};
}
handleChange = e => {
let target = e.target;
let value = target.value;
this.props.setSelectedTheme(value);
};
render() {
return (
<div className="partial-designer-panel-material-size">
<div>
<div className="label-input">
<div className="label">THEME</div>
<div className="input">
<Select
name="selection"
value={this.state.selection}
data={this.props.themeList}
style={{ width: "100%" }}
onChange={this.handleChange}
/>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = appState => {
return {
themeList: appState.appConfig.themeList,
selectedTheme: appState.appConfig.selectedTheme,
};
};
const mapDispatchToProps = dispatch => {
return {
setThemeList: themeList => dispatch(setThemeList(themeList)),
setSelectedTheme: selectedTheme => dispatch(setSelectedTheme(selectedTheme)),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(PanelMaterialSize);
关于如何使第 2 点发挥作用有什么想法吗?
如果可能,请在 fork 的 Codesandbox.io
上提供您的解决方案。
谢谢!
最佳答案
Updater
组件每 3 秒生成新的主题列表
它还必须调度 setSelectedTheme
操作来更新应用程序状态中选定的主题
关于javascript - 无法使用 React 和 Redux 从自定义组件更新应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860229/