简体   繁体   English

更新数组 useState 反应钩子(Next.js)

[英]updating array useState react hooks (Next.js)

I am trying to update my 'state' array and insert items of type String into it with 'setState' but it doesn't works.我正在尝试更新我的“状态”数组并使用“setState”将字符串类型的项目插入其中,但它不起作用。
I know it's not work with push().我知道它不适用于 push()。
I also tried to update my 'state' array with the spread operator but it also doesn't work.我还尝试使用扩展运算符更新我的“状态”数组,但它也不起作用。
Here my code:这是我的代码:

import React, { useState } from 'react';
import _, { debounce } from 'lodash';


export default function Search() {

  const [state, setState] = useState([])

  const handleChange = debounce(async (value) => {
    const url = `http://localhost:3100/`
    if (value == '') {
      return
    }
    let response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify({ value })
    })

    let test = await response.json()
    console.log(test)

    setState(state.concat(test))
    // setState([...state, test]) it also doesn't work
    console.log(state)    
  }, 1000)

  return (
    <>
      <div>
        <input onChange={e => handleChange(e.target.value)} />
      </div>
    </>
  )
}

The 'state' array remains empty. “状态”数组保持为空。 I need to understand why please.我需要了解为什么。

1.) Change if(value == '') to if(value ==='') 1.) 将if(value == '')更改为if(value ==='')

2.) console.log(state) after your setState will return the previous value of state as the component has not refreshed yet. 2.) console.log(state)在你的 setState 之后将返回 state 之前的值,因为组件还没有刷新。 Look at the example here: https://codesandbox.io/s/friendly-ives-vvo13?file=/src/App.js:103-474 and type something and look at the console.查看此处的示例: https://codesandbox.io/s/friendly-ives-vvo13?file=/src/App.js:103-474并输入一些内容并查看控制台。 Then type something else and look at the console.然后输入其他内容并查看控制台。 You will see the console is showing the state of what you previous typed.您将看到控制台显示您之前输入的 state。 However, if you look at the {state} rendered inside of the return, it will show you the current state.但是,如果您查看返回内部呈现的 {state},它将显示当前的 state。

    export default function App() {
  const [state, setState] = useState([]);

  const handleChange = debounce(async value => {
    let test = ["cars", "boat", "bike"];

    setState([...test, value]);
    console.log(state);
  }, 1000);

  return (
    <>
      <div>
        {state}
        <input onChange={e => handleChange(e.target.value)} />
      </div>
    </>
  );
}

So you are setting state, just accessing/reading it in the wrong place.因此,您正在设置 state,只是在错误的位置访问/读取它。

https://codesandbox.io/s/next-js-infinite-scroll-3vfem?file=/pages/Content.js https://codesandbox.io/s/next-js-infinite-scroll-3vfem?file=/pages/Content.js

I added one line to this function from the demo above我从上面的演示中向这个 function 添加了一行

const getMorePost = async () => {

      const res = await fetch(
        `https://jsonplaceholder.typicode.com/todos?_start=${posts.length}&_limit=20`
      );

      const newPosts = await res.json()

      setHasMore(!!newPosts.length)

      setPosts((post) => [...post, ...newPosts])
    }

now scroll completes ok.现在滚动完成。

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

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