立即更新 useState [英] Update useState immediately
问题描述
useState
不会立即更新状态.
我正在使用 react-select 并且我需要使用 (multi
) 根据请求结果选择的选项.
出于这个原因,我创建了状态 defaultOptions
,以存储 queues
常量的值.
原来在加载组件的时候,数值只显示了第二次.
我在queues
中做了一个console.log
,返回的不是空的.
我对 defaultOptions
状态做了同样的处理,返回为空.
为了更好,我创建了一个 codesandbox观看.
const 选项 = [{标签:队列 1",值:1},{标签:队列 2",值:2},{标签:队列 3",值:3},{标签:队列 4",值:4},{标签:队列 5",值:5}];const CustomSelect = (props) =><选择类名=自定义选择"{...道具}/>;const baseUrl =https://my-json-server.typicode.com/wagnerfillio/api-json/posts";const App = () =>{常量用户 ID = 1;常量初始值 = {名称:"};const [user, setUser] = useState(initialValues);const [defaultOptions, setDefaultOptions] = useState([]);const [selectedQueue, setSelectedQueue] = useState([]);useEffect(() => {(异步() => {如果 (!userId) 返回;尝试 {const { data } = await axios.get(`${baseUrl}/${userId}`);setUser((prevState) => {return { ...prevState, ...data };});const queues = data.queues.map((q) => ({值:q.id,标签:q.name}));//这里有一个不同于空虚的结果控制台日志(队列);设置默认选项(队列);} 抓住(错误){控制台日志(错误);}})();返回 () =>{设置用户(初始值);};}, []);//这是一个空结果控制台日志(默认选项);const handleChange = async (e) =>{const value = e.map((x) => x.value);控制台日志(值);setSelectedQueue(value);};返回 (多选:<自定义选择选项={选项}默认值={默认选项}onChange={handleChange}是多的/>);};导出默认应用程序;
React 不会在调用 setState 时立即更新状态,有时可能需要一段时间.如果你想在设置新状态后做一些事情,你可以使用 useEffect 来确定状态是否像这样改变:
const [ queues, setQueues ] = useState([])useEffect(()=>{/* 当队列确实更新时它会被调用 */},[队列] )const someHandler = ( newValue ) =>设置状态(新值)
useState
does not update the state immediately.
I'm using react-select and I need to load the component with the (multi
) options selected according to the result of the request.
For this reason, I created the state defaultOptions
, to store the value of the queues
constant.
It turns out that when loading the component, the values are displayed only the second time.
I made a console.log
in the queues
and the return is different from empty.
I did the same with the defaultOptions
state and the return is empty.
I created a codesandbox for better viewing.
const options = [
{
label: "Queue 1",
value: 1
},
{
label: "Queue 2",
value: 2
},
{
label: "Queue 3",
value: 3
},
{
label: "Queue 4",
value: 4
},
{
label: "Queue 5",
value: 5
}
];
const CustomSelect = (props) => <Select className="custom-select" {...props} />;
const baseUrl =
"https://my-json-server.typicode.com/wagnerfillio/api-json/posts";
const App = () => {
const userId = 1;
const initialValues = {
name: ""
};
const [user, setUser] = useState(initialValues);
const [defaultOptions, setDefaultOptions] = useState([]);
const [selectedQueue, setSelectedQueue] = useState([]);
useEffect(() => {
(async () => {
if (!userId) return;
try {
const { data } = await axios.get(`${baseUrl}/${userId}`);
setUser((prevState) => {
return { ...prevState, ...data };
});
const queues = data.queues.map((q) => ({
value: q.id,
label: q.name
}));
// Here there is a different result than emptiness
console.log(queues);
setDefaultOptions(queues);
} catch (err) {
console.log(err);
}
})();
return () => {
setUser(initialValues);
};
}, []);
// Here is an empty result
console.log(defaultOptions);
const handleChange = async (e) => {
const value = e.map((x) => x.value);
console.log(value);
setSelectedQueue(value);
};
return (
<div className="App">
Multiselect:
<CustomSelect
options={options}
defaultValue={defaultOptions}
onChange={handleChange}
isMulti
/>
</div>
);
};
export default App;
React don't update states immediately when you call setState, sometimes it can take a while. If you want to do something after setting new state you can use useEffect to determinate if state changed like this:
const [ queues, setQueues ] = useState([])
useEffect(()=>{
/* it will be called when queues did update */
},[queues] )
const someHandler = ( newValue ) => setState(newValue)
这篇关于立即更新 useState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!