Javascript React-从URL获取并在组件加载时设置状态

Javascript React-从URL获取并在组件加载时设置状态,javascript,node.js,reactjs,react-native,Javascript,Node.js,Reactjs,React Native,我正在使用React Native编写一个应用程序,我发现了一些奇怪的错误。 我想获取“应用程序加载”中用户的国家/地区,更新状态,然后在组件的其他地方使用状态。听起来很简单,但我总是出错 对于这个特定的代码,我得到未定义的不是对象(计算'this.state') 我做错了什么?我该怎么做才对呢 (我使用API是因为我不想请求位置权限) 导出默认函数App(){ 状态={ 国家代码:“美国”, } useffect(()=>{ 取('https://ipapi.co/json/') .then(

我正在使用React Native编写一个应用程序,我发现了一些奇怪的错误。 我想获取“应用程序加载”中用户的国家/地区,更新状态,然后在组件的其他地方使用状态。听起来很简单,但我总是出错

对于这个特定的代码,我得到未定义的不是对象(计算'this.state')

我做错了什么?我该怎么做才对呢

(我使用API是因为我不想请求位置权限)

导出默认函数App(){
状态={
国家代码:“美国”,
}
useffect(()=>{
取('https://ipapi.co/json/')
.then(response=>response.json())
.then(data=>this.setState({countryCode:data.country_code}));
}, []);
返回(
// ...
);
}

功能组件没有此
。功能组件中不存在this.setState
这样的东西。相反,您必须使用
useState
,它不使用实例的属性,而是在函数体中使用普通的独立变量(以及状态设置器函数作为另一个独立变量):

export default function App() {
  const [countryCode, setCountryCode] = useState('US');


  useEffect(() => {
    fetch('https://ipapi.co/json/')
      .then(response => response.json())
      .then(data => setCountryCode(data.country_code));
  }, []);


  return (
    <View style={styles.container}>
      // ...
    </View>
  );
}
导出默认函数App(){
const[countryCode,setCountryCode]=useState('US');
useffect(()=>{
取('https://ipapi.co/json/')
.then(response=>response.json())
.then(data=>setCountryCode(data.country_code));
}, []);
返回(
// ...
);
}

功能组件没有此
。功能组件中不存在this.setState
这样的东西。相反,您必须使用
useState
,它不使用实例的属性,而是在函数体中使用普通的独立变量(以及状态设置器函数作为另一个独立变量):

export default function App() {
  const [countryCode, setCountryCode] = useState('US');


  useEffect(() => {
    fetch('https://ipapi.co/json/')
      .then(response => response.json())
      .then(data => setCountryCode(data.country_code));
  }, []);


  return (
    <View style={styles.container}>
      // ...
    </View>
  );
}
导出默认函数App(){
const[countryCode,setCountryCode]=useState('US');
useffect(()=>{
取('https://ipapi.co/json/')
.then(response=>response.json())
.then(data=>setCountryCode(data.country_code));
}, []);
返回(
// ...
);
}