React 和构建地理应用程序的新手。uniqueRegions = ['Asia', 'America', 'Europe', 'Africa', 'Oceania', 'Polar']
我的道具中有一系列大陆
作为this.props.uniqueRegions
. 在我的组件中,我想visible
在每个大陆上设置属性的状态。我可以对其进行硬编码,但我不想这样做。我怎么可能做到这一点?
我尝试使用扩展运算符
state = {
[ ...this.props.uniqueRegions]: {visible: 5}
};
但这显然是不正确的语法。
另外,我尝试在 setState 中初始化可见属性,但它总是返回未定义。
loadMore = (region) => {
console.log(this.state[region])
if(this.state[region])
this.setState(prevState => ({
[region]: {visible: 5}
}))
}
下面是我的区域数据是如何传递并当前设置为状态的。
filterRegion = (region) =>{
if(region !==undefined ){
this.setState({
[region]: {countries: ['']}
})
return Axios
.get('https://restcountries.eu/rest/v2/region/' + region)
.then(res => {
if(res.status === 200 && res !== null){
this.setState(prevState =>({
[region]: {...prevState[region],
countries: (res && res.data || [])}
}))
} else {
throw new Error('No country found');
}
})
.catch(error => {
console.log(error)
return []
});
};
};
loadMore = (region) => {
console.log(this.state[region])
if(this.state[region])
this.setState(prevState => ({
[region]: {visible: 5}
}))
}
render(){
const handleRegion =(region) =>{
this.filterRegion(region);
if(this.state[region] && this.state[region].open){
this.setState(prevState =>({
[region]: {...prevState[region],
open: false
}
}))
} else {
this.setState(prevState =>({
[region]: {...prevState[region],
open: true
}
}))
}
}
我已经能够在特定区域(即 [region].open)上设置属性,但似乎无法使其可见。
编辑/问题已解决
在与 Junius 来回折腾之后,我调整了我的代码。为我解决的问题是设置一个变量,该变量包含我想要的每个数组元素的所有属性,将它们添加到数组中,然后使用扩展运算符将整个数组设置为状态。
if (!regions) {
console.log('no regions')
return;
}
if(regions)
console.log(regions);
const regionsState = {};
regions.forEach((region, index) => {
if(this.state[region] && this.state[region].countries[0]){
regionsState[region] = { visible: 5, countries: this.state[region].countries, open: false};
} else {
this.filterRegion(region);
regionsState[region] = { visible: 5, countries: [], open: false};
}
});
// set state here outside the foreach function
this.setState((prevState => ({
...regionsState
})))
};
最后,我无法正确初始化数据。起初,我是通过点击加载数据,但这既不理想也不现实;加载道具后,在componentDidMount中运行代码不会触发。我的解决方案是在componentDidUpdate中运行该函数。我的状态现在正确初始化。再次感谢朱尼乌斯的帮助!