javascript - 字符串数组未在反应中呈现
问题描述
每次从下拉列表中选择一个选项时,我都希望看到我的数组呈现。但是,它不会立即显示更改下拉列表中的元素。我该如何解决这个问题?
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
解决方案
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>
));
}
推荐阅读
- ios - 购买历史记录中的应用内购买待处理
- android - 如果 android 中的文本较少,则标记文本不会移动
- php - 表单提交后如何保留上一页的php变量
- android - 当我加载 pdf url 时,Webview 有时看起来像白色或透明
- vba - 将Word文档拆分为单独文件的最快方法
- java - 为 CloudFoundry Java CLI 实现 TokenProvider 的问题
- reactjs - 强制更新 React@16.8.6 中的所有组件
- perl - 从字符列表生成所有组合
- php - 我在整数上收到对成员函数 addEagerConstraints() 的错误调用
- java - 如何通过 ID 从数据库 Spring Boot Java REST API 获取数据