我有一个非常基本的 ReactJS
应用程序,它使用包含以下组件的 Redux
:
PanelMaterialSize > 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 } from '../../store/AppConfig/actions';
class PanelMaterialSize extends Component {
componentDidMount() {
this.n = 1;
setInterval(() => {
let themeList = [
{ value: this.n, text: 'Option ' + this.n },
{ value: this.n + 1, text: 'Option ' + (this.n + 1) },
{ value: this.n + 2, text: 'Option ' + (this.n + 2) },
];
this.props.setThemeList(themeList);
this.n += 3;
}, 1000);
}
render() {
return (
<div className="partial-designer-panel-material-size">
<div>
<div className="label-input">
<div className="label">MATERIAL</div>
<div className="input">
<Select data={this.props.themeList} style={{ width: '100%' }} />
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (appState) => {
return {
themeList: appState.appConfig.themeList,
}
}
const mapDispatchToProps = (dispatch) => {
return {
setThemeList: (themeList) => dispatch(setThemeList(themeList)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PanelMaterialSize);
在我看来 Redux
逻辑很好,因为我已经通过做几件事进行了测试。
我的问题是,当调用 PanelMaterialSize
的 render(...)
方法时,组件:Select
不会使用新数据(每一秒更改一次)呈现。
这里有一个可以玩的 Codesandbox.io
(最好使用 Chrome
):
https://codesandbox.io/s/03mj405zzv
关于如何正确更改其内容的任何想法?
如果可能的话,请提供一个新的 Codesandbox.io
和你的解决方案,从之前的解决方案中 fork 出来。
谢谢!
最佳答案
问题出在您的选择组件中。 您正在传递最初为空的数组并使用 this.state.data Prop 检查您的组件,下次 reducer 更改您的 this.state.data 将不会更新数据。因为你在构造函数中初始化。构造函数只在组件挂载时调用一次。
问题出在您选择的渲染方法中:
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">
//change data with this.props.data
{this.props.data.length > 0 &&
this.props.data.map((elem, index) => {
return (
<option value={elem.value} key={index}>
{elem.text}
</option>
);
})}
</select>
</div>
</div>
);
}
关于javascript - 自定义组件无法在此基本 ReactJS 应用程序上正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821440/