reactjs - 反应没有使用类中的状态更新组件
问题描述
所以首先我试图将空值分配给状态组件,然后再为它们分配值所以这是我的类的构造函数
constructor(props){
super(props);
this.state = {
Countrys:null,
States:null,
Citys:null
}
}
然后我为它们分配值是 ComponentDidUpdate 函数所以这是我的 componentDidMount 函数
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position)
console.log("Latitude is :", position.coords.latitude);
console.log("Longitude is :", position.coords.longitude);
});
this.setState({
Countrys:Country.getAllCountries(),
States:State.getAllStates(),
Citys:City.getAllCities()
})
/*console.log("Country:: "+Country.getAllCountries()[0].name);
console.log("City:: "+City.getAllCities()[0].name);*/
}
然后我试图在我的 jsx 元素中访问它们作为回报,使用这样的地图
{this.state.Citys.map((ele ,index) =>
<option value={`${ele}`} className="d-inline mx-2 col-sm-5" onClick={({target}) => target.classList.toggle('bg-primary')}>
{ele.name}
</option>
)}
但它向我展示了错误
TypeError: Cannot read properties of null (reading 'map')
谁能告诉我这里出了什么问题或如何纠正它,当我尝试将类似 City.getAllCities() 的函数直接分配给 this.state 而不是将它们分配为 null 时,它显示页面无响应
而 City.getAllCities()、Country.getAllCountries()、State.getAllStates() 来自 npm 包“country-state-city”
解决方案
如果像您提到的那样,您使用的是country-state-city,那么没有理由将这三个值推迟到根本加载componentDidMount
:它们是从country-state-city
包中静态导入的。
只需将它们导入文件顶部,在构造函数中创建初始状态,分配这些值,然后null
在渲染期间就完成了没有任何状态的操作。
import { Component } from "react";
import { Country, State, City } from "country-state-city";
...
export class YourClass extends Component {
constructor(props) {
super(props);
this.state = {
countries: Country.getAllCountries(),
states: State.getAllStates(),
cities: City.getAllCities()
};
}
render() { ... }
}
推荐阅读
- vue.js - CoreUi - 为什么 nightwatch 不能运行 e2e 测试?
- javascript - 在 jQuery 变量中传递参数
- go - 如何在 gin-gonic 和 nrgin 中的 New Relic 中捕获自定义错误消息
- zend-framework2 - EntityManager persist 期望参数 1 是一个实体对象,NULL 给定 zend 教义
- android - 为什么我的图标在安卓设备上被拉伸?
- javascript - Firebase Auth:当用户密码/电子邮件不正确时,不会出现错误消息。快速解决?
- kotlin - Kotlin 多平台项目依赖项
- python-3.x - 在列表中查找相同的值并删除重复的错误输出
- python - matplotlib/mplot3d scatterplot 尊重掩蔽,但surfaceplot 没有 - 为什么?
- c++ - C++ 的文件 I/O