我有这样的状态:
const [data, setData] = useState[{name:"abc", gender: "male", experience: ["a","b","c"]}];
我有经验显示功能
const display= () => {
let items = data.experience;
return items.map((val,ind) => {
return(<li key={ind}>{val}</li>);
});
}
如果我删除了经验值,则状态会随着新的项目数组而改变,但是我的组件未随着更新的项目而更新,我该如何解决这个问题
删除功能:(它可以正常工作并且状态发生变化,但是组件没有重新呈现新状态)
const deleteExperience = (ind) => {
let newData = data;
let experiences = newData.experience.filter((val, id) => id !== ind);
newData.experience = experiences;
setData(newData);
};
答案 0 :(得分:0)
尝试一下-您可以像这样删除
export default function App() {
const [data, setData] = React.useState({
name: "abc",
gender: "male",
experience: ["a", "b", "c"]
});
const deleteIt = id => {
let filtered = data.experience.filter(filt => filt !== id);
setData({
...data,
experience: filtered
});
};
return (
<div className="App">
<ul>
{data.experience.map(d => (
<li key={d} onClick={() => deleteIt(d)}>
<h3>{d}</h3>
</li>
))}
</ul>
</div>
);
}
答案 1 :(得分:0)
如何删除阵列?如果使用拼接删除索引。 有时,您会在数组中的实际数据发生更改之前调用setState,因此,在对setTimeout
之类的操作稍加延迟之后,尝试调用setStatesetTimeout(function(){
// call your setState here with new data
}, 1000);
答案 2 :(得分:0)
我已修复它,问题出在删除功能中:
const deleteExperience = (ind) => {
let newData = data;
let experiences = newData.experience.filter((val, id) => id !== ind);
newData.experience = experiences;
setData(newData);
};
更正(应使用对象散布),因为=符号不会创建新数组,而是会创建对原始数组的引用:
const deleteExperience = (ind) => {
let newData = {...data};
let experiences = newData.experience.filter((val, id) => id !== ind);
newData.experience = experiences;
setData(newData);
};