如何在无状态组件中合并值?

更新状态变量总是代替它而不是合并它。 如何合并呢? 函数addFruits接收多个对象,例如: {fruitName:香蕉} {fruitName:苹果} {fruitName:西瓜}

如何将这个fruitName推入水果状态?

因为下面的代码始终返回最后的fruitName。但是如何合并所有fruitsName?像array.push(val);

code bold italic

const [fruits, setFruits] = useState([]); // this is state
    function addFruits(value){
    Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(res => { // this method gives me multiple object, (like {fruitName: banana} {fruitName: apple} {fruitName: watermelon})
        res.map(result => {
            setProps(result.fruitName); 
        })
    })
}
评论
依賴你所有
依賴你所有

You need to combine the existing fruits array with the result from the API:

.then((res) => {
  setFruits([
    ...fruits,
    ...res.map(fruit => fruit.fruitName)
  ]);
});
点赞
评论
esaepe
esaepe

您可以将响应与状态合并-

function addFruits(value){
    Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(response => {
           totalFruits = [...fruits,
             ...response.map(fruit => fruit.fruitName)]
          setFruits(totalFruits);
        })
    })
点赞
评论