简体   繁体   English

Array.push() function 在 React JS 中不起作用

[英]Array.push() function not working in React JS

I have an object which represents a recipe, whenever I click the "Add" button my function is supposed to add that corresponding recipe to an empty object array, but oddly only on recipe object gets added to the empty array and when i try to add more than one then it throw this at me: favList.push is not a function. I have an object which represents a recipe, whenever I click the "Add" button my function is supposed to add that corresponding recipe to an empty object array, but oddly only on recipe object gets added to the empty array and when i try to add不止一个然后它扔给我:favList.push 不是 function。

My HTML Code:我的 HTML 代码:


import React from 'react'
import './home.css'

const Home = (props) => {
return <div className="home">
               
                     <div className="wrapper">
                            {props.items.map((item) => {
                                  return  <div className="flexIt">
                                                    {item.ingredients.map((ingredient) => 
                                                        <ol>
                                                            <li>{ingredient}</li>
                                                        </ol>
                                                    )}        
                                                </div>
                                            </div>
                                            <div className="closeBtn">
                                                <button onClick = {() => {props.onRemove(item)}} >X</button>
                                                <button onClick = {() => {props.addItemToFav(item)}} >Add</button>
                                            </div>
                                          </div>})}
                            </div>
                     </div> 
                </div>
            </div>
}

export default Home

My JavaScriipt code:我的 JavaScript 代码:


import './App.css';
import Home from './components/Home';
import AddRecipe from './components/AddRecipe';
import { useNavigate } from 'react-router'
import items from './data';
import React, { useState } from 'react';
import {Routes, Route} from 'react-router-dom';

    const App = () => {
    const navigate = useNavigate(); 
    const [favList, setFavList] = useState([]);
    
  const addToFav = (itemToBeAdded) => {
      setFavList(favList.push([itemToBeAdded]));
      console.log(favList);   
  }
  return (

      <Routes>
        <Route exact path="/" element={<Home onRemove={removeItem} addItemToFav={addToFav} items={itemsList}/>} />
        <Route path="/addRecipe" element={<AddRecipe onAddRecipe={(newRecipe) => {
        addRecipe(newRecipe);
        navigate('/');
      }}
    />} />
        </Routes>
  );
}

export default App;

***

First, push will mutate the existing array.首先, push将改变现有的数组。

Then you pass the return value to setFavList (which is a number representing the length of the array).然后将返回值传递给setFavList (这是一个表示数组长度的数字)。

You need to pass a new array to setFavList .您需要将一个新数组传递给setFavList You can't (usefully) pass that number or the original (but mutated) array (since it would detect it is the same array and do nothing).您不能(有用地)传递该数字或原始(但突变的)数组(因为它会检测到它是同一个数组并且什么都不做)。

For example:例如:

const addToFav = (itemToBeAdded) => {
  const replacementList = [...favList, itemToBeAdded];
  setFavList(replacementList);
}

(Note also that itemToBeAdded probably shouldn't be wrapped in an extra array.) (还要注意itemToBeAdded可能不应该被包装在一个额外的数组中。)

Then your attempt to log the new value needs to be moved because addToFav will have closed over the original value.然后需要移动您记录新值的尝试,因为addToFav将关闭原始值。 This is explained by answers to this question这可以通过这个问题的答案来解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM