gpt4 book ai didi

javascript - React 组件的 map 在状态更改时不会重新渲染

转载 作者:行者123 更新时间:2023-11-28 16:56:54 25 4
gpt4 key购买 nike

我有一个设置,其中有一张需要在 View 中显示的 React 组件图。

还有许多输入选择处理程序会更新父组件状态,但在状态更新后,会调用父组件渲染方法,但子组件不会刷新值。

我在这里缺少什么?我有点困惑

问题的最小重现 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'));

最佳答案

类字段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 返回的数据始终是最新的。

关于javascript - React 组件的 map 在状态更改时不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58905264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com