附加数组值而不是 React 中显示的新值列表

Array value appended instead of new value list display in React

场景-

文本字段中的默认输入数字 - 1

列出的项目 -

现在,一旦我从文本字段中删除 1 -

列表项 -

现在在输入栏中输入4

列表项 -

预期行为 -

列表项应仅显示 - 4, 9 and 14 而不是 NaN, NaN, 4, 9, 14

让我知道我做错了什么。

代码-

import React, { useState } from "react";
import List from "./List";

const ReRendering = () => {
  const [number, setNumber] = useState(1);

  const getList = () => [number, number + 5, number + 10];

  return (
    <div>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(parseInt(e.target.value, 10))}
      />
      <div>
        <List getList={getList} />
      </div>
    </div>
  );
};

export default ReRendering;

List.js

import { useEffect, useState } from "react";

const List = ({ getList }) => {
  const [item, setItem] = useState([]);

  useEffect(() => {
    setItem(getList());
  }, [getList]);
  return (
    <div className="list">
      {item.map((x) => (
        <div key={x}>{x}</div>
      ))}
    </div>
  );
};

export default List;

工作示例 - https://codesandbox.io/s/gallant-gagarin-l18ni1?file=/src/ReRendering.js:0-463

如果输入字段为空,则执行 setNumber(parseInt(e.target.value, 10)) 会将数字状态设置为 NaN,因为空字符串不能 parseIntd.

console.log(parseInt(''));

而 NaN 会导致问题,因为正如 React 警告所说:

Warning: Encountered two children with the same key, NaN. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

重复的 NaN 会导致重复的键。

相反,使用 valueAsNumber,如果该值不存在,则用 0 替代。

const { useState, useEffect } = React;
const ReRendering = () => {
  const [number, setNumber] = useState(1);

  const getList = () => [number, number + 5, number + 10];

  return (
    <div>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(e.target.valueAsNumber || 0)}
      />
      <div>
        <List getList={getList} />
      </div>
    </div>
  );
};

const List = ({ getList }) => {
  const [item, setItem] = useState([]);
  useEffect(() => {
    setItem(getList());
  }, [getList]);
  return (
    <div className="list">
      {item.map((x) => (
        <div key={x}>{x}</div>
      ))}
    </div>
  );
};


ReactDOM.render(<ReRendering />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

更好的构造方法是立即在子对象中调用 getList,而不是在其中使用单独的状态和效果挂钩。

const { useState, useEffect } = React;
const ReRendering = () => {
  const [number, setNumber] = useState(1);

  const getList = () => [number, number + 5, number + 10];

  return (
    <div>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(e.target.valueAsNumber || 0)}
      />
      <div>
        <List getList={getList} />
      </div>
    </div>
  );
};

const List = ({ getList }) => (
  <div className="list">
    {getList().map((x) => (
      <div key={x}>{x}</div>
    ))}
  </div>
);


ReactDOM.render(<ReRendering />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

我认为这是因为空输入的值是空字符串,parseInt 不知道如何处理,因此 returns NaN。 我认为您需要创建一个函数来处理该问题,如果输入的值为空字符串,则将状态设置为 0。类似于:

const handleChange = (e) => {
  const value = e.target.value;
  setNumber(value === '' ? 0 : Number(value));
}

另外我想我应该让您知道您不需要 <List /> 组件中的 useStateuseEffect。您的列表可以在道具更改时更新,因此您可以像这样进行映射:getList().map(...rset of the code)

进行以下更改,结果应该正是您要查找的内容。

它基本上考虑了输入为空的情况,并告诉它在没有提供输入时显示 none。

List.js


import { useEffect, useState } from "react";

const List = ({ getList }) => {
  const [item, setItem] = useState([]);

  useEffect(() => {
    setItem(getList());
  }, [getList]);
  return (
    <div className="list">
      {item ? item.map((x) => (               // changes
        <div key={x}>{x}</div>
      )):""}
    </div>
  );
};

export default List;


ReRendering.js

import React, { useState } from "react";
import List from "./List";

const ReRendering = () => {
  const [number, setNumber] = useState(1);

  const getList = () => {
    if(number === ""){                     // changes
      return;
    }
    return [number, number + 5, number + 10];
  };

  return (
    <div>
      <input
        type="number"
        value={number}
        onChange={(e) => {
          if (e.target.value !== "") {               //changes
            setNumber(parseInt(e.target.value, 10));
          } else {
            setNumber(""); 
          }
        }}
      />
      <div>
        <List getList={getList} />
      </div>
    </div>
  );
};

export default ReRendering;

我相信已经回答了你的-

Let me know what I am doing wrong here.

查看您对输入字段中 0 零问题的评论,我认为您可以修改 getList() 方法,进行数字检查并在数字为空时传递空白数组.

改变你的 getList() 方法 -

const getList = () => number ? [number, number + 5, number + 10] : [];