gpt4 book ai didi

javascript - map 不返回正确的对象数组

转载 作者:行者123 更新时间:2023-11-30 14:15:45 25 4
gpt4 key购买 nike

尝试做一个映射来将 selected 的值设置为 true 和 false,但它并没有改变现有的 true 值,出了什么问题?

selectTab = tab => e => {
const { data } = this.state;
this.setState(
{
data: data.map(o =>
o.tab === tab ? { selected: true, ...o } : { selected: false, ...o }
)
},
() => console.log(this.state.data)
);
};

https://codesandbox.io/s/885l8q537l

最佳答案

首先尝试展开对象,然后添加selected 属性。否则 o 中的 selected 属性每次都会覆盖它。

selectTab = tab => e => {
this.setState(
prevState => ({
data: prevState.data.map(o =>
o.tab === tab ? { ...o, selected: true } : { ...o, selected: false }
)
}),
() => console.log(this.state.data)
);
};

class App extends React.Component {
state = {
data: [
{
tab: 1,
content: "Tab 1 content",
selected: true
},
{
tab: 2,
content: "Tab 2 content"
},
{
tab: 3,
content: "Tab 3 content"
}
]
};

selectTab = tab => e => {
this.setState(
prevState => ({
data: prevState.data.map(o =>
o.tab === tab ? { ...o, selected: true } : { ...o, selected: false }
)
}),
() => console.log(this.state.data)
);
};

render() {
const { activeTab, data } = this.state;
return (
<div>
{data.map(obj => (
<div onClick={this.selectTab(obj.tab)}>{obj.tab}</div>
))}
{data.map(obj => (
<div>{obj.selected && obj.content}</div>
))}
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - map 不返回正确的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53586239/

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