首页 > 解决方案 > 反应没有使用类中的状态更新组件

问题描述

所以首先我试图将空值分配给状态组件,然后再为它们分配值所以这是我的类的构造函数

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”

标签: reactjs

解决方案


如果像您提到的那样,您使用的是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() { ... }
}

推荐阅读