简体   繁体   English

setState 在反应 js 的功能组件中不起作用

[英]setState is not working in functional component in react js

I want to display the name based on user click.我想根据用户点击显示名称。 when browse button will click we will show list of name and if we click the name then i want to display the name with changing the state.单击浏览按钮时,我们将显示名称列表,如果我们单击名称,那么我想通过更改 state 来显示名称。

here is the sample code这是示例代码

 const TestCli = () => { const [names, setfolderName] = React.useState([ "sonu", "monu", "xyz", "abc", "lol", ]); const [isdiv, setisdiv] = React.useState(false); const [Name, setName] = React.useState("My name is:"); const [isName, setisName] = React.useState(false); const displayFolder = () => { setisdiv(true); }; const displayInfo = (name) => { setisdiv(;isdiv); setisName(true); setName("My nameis " + name). console;log(Name); }. return ( <React?Fragment> <div>My name is sonu</div> <button class="browseBtn" onClick={displayFolder}> Browse </button> {isdiv. ( <div> {names.map((name) => ( <React.Fragment> <span onClick={() => displayInfo(name)}>{name}</span> <br></br> </React:Fragment> ))} </div> )? null} {isName: <div>{Name}</div>. null} </React;Fragment> ); }. ReactDOM,render(<TestCli />. document;getElementById("root"));
 <div id="root" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

Here printing is successful but when I print on console, it is printing wrong.这里打印成功,但是当我在控制台上打印时,打印错误。 for example: when I first time clicks on any name then it is printing My name is: only.例如:当我第一次点击任何名字时,它正在打印我的名字是:只有。 then when 2nd time clicks on any name whatever previously clicked that name is printing.然后当第二次单击任何名称时,之前单击该名称的任何内容都将打印。

The state is not reflecting state 没有反映

The reason it is happening is because, you are trying to print Name which is a state, but useState hook update setState is asynchronous so by the time it is trying to print the state of it, the value wouldn't have been updated, if you want to console the state, use useEffect passing parameter Name to see actual state发生这种情况的原因是,您尝试打印名称为 state,但 useState 挂钩更新 setState 是异步的,因此当它尝试打印它的 state 时,该值不会被更新,如果你想控制 state,使用 useEffect 传递参数名称来查看实际的 state

useEffect(()=>{
console.log(Name)},[Name])

For What you are trying to achieve, you can refer the below code对于您要实现的目标,您可以参考以下代码


import React, { useState, useEffect } from "react";

const TestCli = () => {
  const names = ["sonu", "monu", "xyz", "abc", "lol"];
  const [isDiv, setIsDiv] = useState(false);
  const [Name, setName] = useState("My name is:" + names[0]);
  const [isName, setIsName] = useState(false);
  const displayFolder = () => {
    setIsDiv(true);
  };
  const displayInfo = (name) => {
    setIsDiv(!isDiv);
    setIsName(true);
    setName(`My name is ${name}`);
    //here you can make axios call
  };
  return (
    <>
      {isName ? <div>{Name}</div> : null}
      <button class="browseBtn" onClick={displayFolder}>
        Browse
      </button>
      {isDiv ? (
        <div>
          {names.map((name) => (
            <>
              <span onClick={() => displayInfo(name)} key={name}>
                {name}
              </span>
              <br></br>
            </>
          ))}
        </div>
      ) : null}
    </>
  );
};

export default TestCli;


You can refer this code sandbox for ref, the code is available at Test.js您可以参考此代码沙箱进行参考,该代码可在 Test.js 获得

编辑 blissful-albattani-x0res

Usually, this can happen because setState is not an immediate command.通常,这可能会发生,因为 setState 不是立即命令。

I checked your code, n here I just changed some unnecessary states you have done there.我检查了您的代码,这里我只是更改了您在那里所做的一些不必要的状态。 For example, you do not need state when you are not change anything, that can be a variable.. check the code:例如,当您不更改任何内容时,您不需要 state,这可以是一个变量.. 检查代码:

  import React, { useState } from "react";

const TestCli = () => {
  const names = ["sonu", "monu", "xyz", "abc", "lol"];
  const [isdiv, setisdiv] = useState(false);

  const [Name, setName] = useState(null);

  return (
    <>
      <div>My name is sonu</div>
      <button class="browseBtn" onClick={() => setisdiv(true)}>
        Browse
      </button>
      {isdiv ? (
        <div>
          {names.map((name) => (
            <div key={name}>
              <span onClick={() => setName("My name is " + name)}>{name}</span>
              <br></br>
            </div>
          ))}
        </div>
      ) : null}

      {Name && <div>{Name}</div>}
    </>
  );
};

export default TestCli;

if something is unclear ask, kindly will help:D如果有不清楚的地方问,请帮助:D

PS. PS。

Also, every list when you map through it should have a unique key.此外,当您通过 map 时,每个列表都应该有一个唯一的键。 in this case i just putted your names as a unique key, but usually, you have an id.在这种情况下,我只是将您的姓名作为唯一键,但通常,您有一个 ID。 Keys help react to tell which item has been changed.. So this may cause some unexpected errors.键有助于做出反应以判断哪个项目已更改。因此这可能会导致一些意外错误。 Read more about keys here: https://reactjs.org/docs/lists-and-keys.html在此处阅读有关密钥的更多信息: https://reactjs.org/docs/lists-and-keys.html

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

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