我有一个设置,其中有一张需要在视图中显示的 React 组件地图。
还有许多输入选择处理程序更新父组件状态,但在状态更新后,父组件渲染方法被调用,但子组件不刷新 Values 。
我在这里错过了什么?我有点困惑
问题Stackblitz 的最小再现。
import React, { PureComponent } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
export const ReactExample = ({ name, value, handleChange }) => (
<select name={name} value={value} onChange={handleChange}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
)
const Section = props => {
return (
<div>
{props.header}
<br />
{props.primaryNode}
<br />
{props.bottom}
</div>
);
};
class App extends React.PureComponent {
state = {
current: 'B'
};
constructor(props) {
super(props);
}
show = [5, 6, 3, 5, 7, 8, 77, 8, 90];
primaryNode = () => {
const filterData = this.show;
return (<div>{filterData}----{this.state.current} // doesn't get updated even though state updates after dropdown</div>);
};
bottom = () => {
return (
<ReactExample name="fruit" value={this.state.current} handleChange={this.handleChange} />
)
}
handleChange = (event) => {
console.log(event.target.value); // always logged and state updated with no change in value
this.setState({ current: event.target.value });
}
data = ["A", "B", "C"];
map = {
"A": (<Section primaryNode={this.primaryNode()} bottom={this.bottom()} header={"A"} />),
"B": (<Section primaryNode={this.primaryNode()} header={"B"} />),
"C": (<Section primaryNode={this.primaryNode()} header={"C"} />)
};
render() {
return (<div>{this.data.map(d => this.map[d])}</div>)
}
}
render(<App />, document.getElementById('root'));
class 字段map
仅初始化一次,在第一次组件渲染时。更改状态并不重要,该变量保存完全相同的数据并且不会及时更改。
解决方案之一是将该变量移动到渲染中:
render() {
const map = {
"A": (<Section primaryNode={this.primaryNode()} bottom={this.bottom()} header={"A"} />),
"B": (<Section primaryNode={this.primaryNode()} header={"B"} />),
"C": (<Section primaryNode={this.primaryNode()} header={"C"} />)
};
return (<div>{this.data.map(d => this.map[d])}</div>)
}
或者您可以将map
字段转换为方法:
map = () => ({
"A": (<Section primaryNode={this.primaryNode()} bottom={this.bottom()} header={"A"} />),
"B": (<Section primaryNode={this.primaryNode()} header={"B"} />),
"C": (<Section primaryNode={this.primaryNode()} header={"C"} />)
});
render() {
return (<div>{this.data.map(d => this.map()[d])}</div>)
}
所以返回的数据map
总是最新的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句