gpt4 book ai didi

javascript - 设置后如何获取react中的状态值?

转载 作者:行者123 更新时间:2023-11-28 03:27:41 25 4
gpt4 key购买 nike

在下面的代码中,我试图设置一个 react 状态国家,我需要在设置后立即使用它。现在我只得到国家变量中先前的状态值。有没有办法在设置后立即获取国家值?比如回调或 promise ?

import React,{useState,useEffect} from 'react';
import Axios from 'axios';


const url = 'https://restcountries.eu/rest/v2/name/'
let renderData= <div id="result"><h4>no Data </h4></div>

const Search = () =>
{

const [country,setCountry]=useState('');
const setCountryState = () =>
{
setCountry(event.target.value);
somefunction(country); //I am calling Some Other function Here by passing country as variable
}

return (
<div>
<form>
<input type="text" value={country} onChange={setCountryState} placeholder="Country Name"/>
</form>
<div>
{country}
</div>
</div>
);

}

export default Search;

最佳答案

setState 异步,因此不会立即更新。

相反,利用 useEffect 并将国家/地区添加为依赖项。每次国家/地区更改时,useEffect 函数都会运行

import React,{useState,useEffect} from 'react';
import Axios from 'axios';


const url = 'https://restcountries.eu/rest/v2/name/'
let renderData= <div id="result"><h4>no Data </h4></div>

const Search = () =>
{

const [country,setCountry]=useState('');

useEffect(()=>{
somefunction(country)
},[country])

const setCountryState = (event) =>
{
setCountry(event.target.value);
}

return (
<div>
<form>
<input type="text" value={country} onChange={setCountryState} placeholder="Country Name"/>
</form>
<div>
{country}
</div>
</div>
);

}

export default Search;

关于javascript - 设置后如何获取react中的状态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58487377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com