[英]Cannot update the app state from custom component using React and Redux
我有以下Codesandbox.io
:
https://codesandbox.io/s/qxkq5vvm1q
这是一个基本的ReactJS / Redux
应用程序。
这里的关键组件是:
一个Select
可以通过以下方式获取其值: Redux (state manager) -> PanelMaterialSize (container) -> 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点起作用的任何想法吗?
如果可能,请在分叉的Codesandbox.io
上提供您的解决方案。
谢谢!
Updater
组件每3秒产生一次新的主题列表
它还必须调度setSelectedTheme
操作以在应用程序状态下更新所选主题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.