首页 > 解决方案 > 字符串数组未在反应中呈现

问题描述

每次从下拉列表中选择一个选项时,我都希望看到我的数组呈现。但是,它不会立即显示更改下拉列表中的元素。我该如何解决这个问题?

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>
  );
}

这是我的代码,codesandbox

标签: javascriptarraysreactjs

解决方案


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>
  ));
}

推荐阅读