簡體   English   中英

字符串數組未在反應中呈現

[英]string array not rendering in react

每次從下拉列表中選擇一個選項時,我都希望看到我的數組呈現。 但是,它不會在下拉列表中更改元素時立即顯示。 我該如何解決這個問題?

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

const removeTags = (tagToRemove, currentTag, setCurrentTag) => {
  let temp = currentTag;
  setCurrentTag(temp.filter(each => each !== currentTag));
};

export default function App() {
  const [currentTag, setCurrentTag] = useState([]);

  return (
    <div>
      <select
        onChange={e => {
          let temp = currentTag;
          temp.push(e.target.value);
          console.log(temp);
          setCurrentTag(temp);
        }}
      >
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select>
      {currentTag !== null
        ? currentTag.map((each, index) => (
            <span
              key={index}
              className="tag"
              style={{ backgroundColor: "white" }}
            >
              <span className="tag is-link" style={{ marginLeft: ".5em" }}>
                {each}
              </span>
              <a
                className="tag is-delete"
                onClick={() => removeTags(each, currentTag, setCurrentTag)}
              />
            </span>
          ))
        : ""}
    </div>
  );
}

這是我的代碼, codeandbox

更新狀態值 setCurrentTag 的函數接受一個新的狀態值

  <select
    onChange={e => {
      setCurrentTag([...currentTag, e.target.value]);
    }}
  >
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>

您的錯誤是改變狀態值並將其傳遞給 setCurrentTag 而不是創建新值

  onChange={e => {
    let temp = currentTag; // currentTag is an array, so temp store reference to that array, and not a new array

    temp.push(e.target.value); // push method changes array temp, which refers to currentTag

    console.log(temp);
    setCurrentTag(temp); // pass the same mutated currentTag array
 }}

https://codesandbox.io/s/st-of-react-array-example-tdts8

要將項目添加到數組狀態,您可以像這樣使用setState

setCurrentTag(old => [...old, newItem]);

並從數組中刪除項目使用如下:

setCurrentTag(old => old.filter(a => a != itemToRemove));

這是沙箱

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

export default function App() {
  const [currentTag, setCurrentTag] = useState([]);

  return (
    <div>
      <select
        onChange={e => {
          let value = e.target.value;
          setCurrentTag(old => [...old, value]);
        }}
      >
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select>
      {currentTag !== null
        ? currentTag.map((each, index) => (
            <span
              key={index}
              className="tag"
              style={{ backgroundColor: "white" }}
            >
              <span className="tag is-link" style={{ marginLeft: ".5em" }}>
                {each}
              </span>
              <a
                className="tag is-delete"
                onClick={() => {
                  setCurrentTag(old => old.filter(a => each !== a));
                }}
              />
            </span>
          ))
        : ""}
    </div>
  );
}
import React, { useState } from "react";
import { isEmpty } from "lodash";

function addTags(e, value, setCurrentTag, setAllSectorsSelected) {
  console.log("in addTags,e,value: ", e, value);
}

const removeTags = (tagToRemove, currentTag, setCurrentTag) => {
  let temp = currentTag;
  setCurrentTag(temp.filter(each => each !== currentTag));
};

export default function App() {
  const [currentTag, setCurrentTag] = useState([]);

  const tagSelector = event => {
    // spreading over the previously added options
    setCurrentTag([...currentTag, event.target.value]);
  };

  console.log({ currentTag });
  return (
    <div>
      <select onChange={event => tagSelector(event)}>
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select>
      <DisplayOption {...{ currentTag, setCurrentTag }} />
    </div>
  );
}

function DisplayOption(props) {
  const { currentTag, setCurrentTag } = props;

  if (isEmpty(currentTag)) return null;

  return currentTag.map((each, index) => (
    <span key={index} className="tag" style={{ backgroundColor: "red" }}>
      <span
        className="tag is-link"
        style={{ marginLeft: ".5em", fontSize: "16px", fontColor: "red" }}
      >
        {each}
      </span>
      <div
        href=""
        className="tag is-delete"
        onClick={() => removeTags(each, currentTag, setCurrentTag)}
      />
    </span>
  ));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM