Чтобы использовать USESTATE крюк, вам нужно будет импортировать его от реагирования.
Вы можете просматривать код Sandbox для более интерактивного способа следовать и беспорядок с кодом (рекомендуется вилкой и попробовать себя): CodeSandbox.
import React, {useState} from "react";
Чтобы отслеживать государство, нам нужно позвонить в USEState крючком с первоначальным значением. Поскольку umestate возвращает массив, мы можем разрушать текущую стоимость состояния и функцию, которая позволяет вам обновить состояние.
Вот что это выглядит так.
// variable name is up to you (state) // then name your function, the variable name but with "set" as a prefix (setState) const [state, setState] = useState([])
Давайте начнем строить базовый компонент. Здесь мы создадим начальное состояние в базовый компонент.
// import React and the useState hook import { useState } from "react"; import "./styles.css"; // component function function SimpleArrayComponent() { // set the initial state (an array of user id's to start with) const [users, setUsers] = useState([1, 5, 8, 14, 20]); export default SimpleArrayComponent;
Давайте добавим кнопку Basic, чтобы изменить состояние и точку в DOM, чтобы увидеть изменение состояния.
// JSX we want to return return ( // parent div to hold the ul and li's);{/* map over the users array */} {users.map((userId) => ( // display an
- element with the userId // each element needs to have a unique key
- {userId}
))} // **optional** if you do not have a unique key (like an id) then you are able to use the array index instead {{users.map((userId, index) => (- {userId}
))} // **end optional**
Это то, что нам придется начать с:
Вы видите, что мы объявили функцию под названием «HandleAndduser». Эта функция еще не существует. Давайте создадим это.
// delcare the function function handleAddUserId() { // it's important to not mutate state directly, so here we are creating a copy of the current state using the spread syntax const updateUsers = [ // copy the current users state // you can also clone an array using users.slice() (see below) ...users, // for simplistic purposes, we are just adding the new length of the array users.length + 1 ]; // // updated the state to the updatedUsers setUsers(updateUsers); // array.slice method // create a copy of the users array const updatedArray = users.slice(); // push the new length value to the copied array updatedArray.push(users.length + 1); // set the new state setUsers(updatedArray); }
Нажмите кнопку «Добавить пользователя», и вы увидите новый элемент списка, добавленный в состояние:
Это быстрое руководство показывает, как настроить базовые значения состояния с использованием массивов и как вы можете вернуть новое значение состояния массива.
Спасибо за прочтение!
Оригинал: “https://dev.to/joelynn/react-hooks-working-with-state-arrays-24di”