试图做一个映射来将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)
);
};
答案 0 :(得分:2)
首先尝试扩展对象,然后添加selected
属性。否则,selected
中的o
属性每次都会覆盖它。
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>