如何解决不明白我的过滤器功能和 React 状态有什么问题
父组件:
class App extends Component {
state = {
colors: []
};
async componentDidMount() {
const fetched = await fetch("./response.json");
const fetchedJson = await fetched.json();
const res = fetchedJson.colors;
this.setState({
colors: res
});
}
filterItems = (name) => {
const lowerCaseName = name.toLowerCase();
const newColors = [...this.state.colors];
const res = newColors.filter((color) => {
const lowerCaseColorName = color.name.toLowerCase();
return lowerCaseColorName.includes(lowerCaseName);
});
this.setState({
colors: res
});
};
render() {
const { colors } = this.state;
return (
<div>
<InputText filterItems={this.filterItems} />
<AllData colors={colors} />
</div>
);
}
}
这是我的子组件:
class Filter extends Component {
state = {
inputVal: ""
};
onChange = (e) => {
this.setState({
inputVal: e.target.value
});
this.props.filterItems(e.target.value);
};
render() {
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
onChange={this.onChange}
value={this.state.inputVal}
/>
</form>
);
}
}
export default Filter;
还有另一个名为 AllData
的子组件,但它的工作只是显示数据并在其上设置样式,所以我不包括在这里。
目前显示的数据只有:
Fire Dragon
Water Horse
Earth Bird
Wood Dog
Wind Cat
这是我的问题:
例如:
当我输入字符串“cat”时,res
变为:[{name: "Wind Cat",id: 5}
但是我通过在键盘上回溯删除了该字符串,res
仍然在 [{name: "Wind Cat",id: 5}
。 为什么不退回所有商品,我该如何解决这个问题?
- 我目前有这个代码:
onChange = (e) => {
this.setState({
inputVal: e.target.value
});
this.props.filterItems(e.target.value);
};
但是,如果我将其更改为:
this.props.filterItems(this.state.inputVal);
和 console.log(name)
在 filterItems
的父组件中输出,每次我输入一个字符串时,似乎 console.logged name
只显示之前的字符。
例如:
如果我输入字符串 c
-> name
将是“”(空)
如果我输入字符串 ca
-> name
将是 c
为什么会这样?
解决方法
发生这种情况是因为您过滤了数组并因此丢失了对象。你可以做的是有 2 个数组,一个包含所有数据,一个包含过滤后的数据。将过滤器应用于包含所有数据的数组并将过滤后的数组设置为结果
,class App extends Component {
state = {
colors: [],filtered: [],};
async componentDidMount() {
const fetched = await fetch("./response.json");
const fetchedJson = await fetched.json();
const res = fetchedJson.colors;
this.setState({
colors: res
});
}
filterItems = (name) => {
const lowerCaseName = name.toLowerCase();
const newColors = [...this.state.colors];
const filtered = newColors.filter(color => {
const parts = color.split(' ').map(part => part.toLowerCase());
return parts.reduce((carry,part) => {
return carry ? carry : part.startsWith(lowerCaseName);
},false);
});
this.setState({
filtered,});
};
render() {
const { colors,filtered } = this.state;
return (
<div>
<InputText filterItems={this.filterItems} />
<AllData colors={filtered ? filtered : colors} />
</div>
);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。