gpt4 book ai didi

javascript - 在 react 中结合两个对象,到目前为止没有成功

转载 作者:行者123 更新时间:2023-12-04 08:13:09 25 4
gpt4 key购买 nike

我正在尝试将两个对象组合在一起,但没有任何运气......我正在使用 es6 中应该使用的扩展运算符。我很确定它与 useState 有关。我将首先向您展示我的对象的 console.logs,然后是代码 :)

CONSOLE.LOGS

对象#1:

Object #1

对象#2:

Object #2

组合对象并记录组合结果后,我只得到对象 #1,如下所示:

Combined Object

我的代码

const PortfolioComponent = () => {

const [clickedElement, setClickedElement] = useState({})
const [stockObject, setStockObject] = useState({})
const [stockData, setStockData] = useState({})

const getStock = () => {
axios.request(stock)
.then( res => {
console.log("2. Object #2 from API: ", res.data)
setStockData(res.data) // HERE I SET THE OBJECT FROM MY API CALL
})
.catch( error => {
console.error(error);
}

const handleOpen = name => { // In this function i call the api function and combine the two objects.

let findClickedStock = props.stocksArray.find(item => item.ticker === name)
setClickedElement(findClickedStock)
getStock();
console.log("1. Object #1: ", findClickedStock)

setTimeout(() => { // Waitning for the api to fetch
setStockObject({...findClickedStock, ...stockData}) // Here i combine the two objects, no success
console.log("3. Combined object - Only gets Object #1...", stockObject)
}, 2000);

setOpen(true);
};

}

export default PortfolioComponent;

最佳答案

来自Hooks API Reference :

注意与类组件中的 setState 方法不同,useState 不会自动合并更新对象。您可以通过将函数更新器形式与对象传播语法相结合来复制此行为:

setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});

此外,请查看 useReducer,通常推荐使用它来管理具有多个子值的状态。

关于javascript - 在 react 中结合两个对象,到目前为止没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65847482/

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