如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?

例如setState推的例子?


当前回答

为了进一步展开, 这里有一些常见的例子。开始:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

在数组的末尾推入元素

setTheArray(prevArray => [...prevArray, newValue])

在对象的末尾推/更新元素

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

在对象数组的末尾推/更新元素

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

将元素推到数组对象的末尾

let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);

这里也有一些实际的例子。 https://codesandbox.io/s/reacthooks-push-r991u

其他回答

你可以在自定义状态的末尾追加数据数组:

  const [vehicleData, setVehicleData] = React.useState<any[]>([]);
  setVehicleData(old => [...old, ...newArrayData]);

例如,在下面,你会看到一个axios的例子:

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        {
          url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
          method: 'get',
        }
      );
      setVehicleData(old => [...old, ...result.data.data]);
    };

    fetchData();
  }, [page]);

如果你想推特定的索引,你可以这样做:

   const handleAddAfterIndex = index => {
       setTheArray(oldItems => {
            const copyItems = [...oldItems];
            const finalItems = [];
            for (let i = 0; i < copyItems.length; i += 1) {
                if (i === index) {
                    finalItems.push(copyItems[i]);
                    finalItems.push(newItem);
                } else {
                    finalItems.push(copyItems[i]);
                }
            }
            return finalItems;
        });
    };

我尝试了上面的方法将一个对象推入useState中的对象数组,但在使用TypeScript时出现以下错误:

类型“TxBacklog[] | undefined”必须有一个“符号”。Iterator的方法,返回一个Iterator .ts(2488)

tsconfig的设置。Json显然是正确的:

{
   "compilerOptions": {
   "target": "es6",
   "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "es6",
],

这个方法解决了问题(我的示例代码):

接口:

   interface TxBacklog {
      status: string,
      txHash: string,
   }

状态变量:

    const [txBacklog, setTxBacklog] = React.useState<TxBacklog[]>();

将新对象推入数组:

    // Define new object to be added
    const newTx = {
       txHash: '0x368eb7269eb88ba86..',
       status: 'pending'
    };
    // Push new object into array
    (txBacklog) 
       ? setTxBacklog(prevState => [ ...prevState!, newTx ])
       : setTxBacklog([newTx]);
// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

最推荐的方法是同时使用包装函数和展开运算符。例如,如果你像这样初始化了一个名为name的状态,

控制[names, setNames] = useState(]

你可以像这样推到这个数组,

setNames(names => [...names, newName])

希望这能有所帮助。