Reactjs 搜索筛选器退格后未更新回的状态
您好,我正在使用filter方法制作一个reactjs搜索过滤器,我的问题是每次我按下backspace,它都不会返回到原始状态,或者在ajax调用后我在componentdidMount中设置的状态,为什么我的状态没有更新回我在componentdidMount中指定的状态 这是我的密码Reactjs 搜索筛选器退格后未更新回的状态,reactjs,axios,Reactjs,Axios,您好,我正在使用filter方法制作一个reactjs搜索过滤器,我的问题是每次我按下backspace,它都不会返回到原始状态,或者在ajax调用后我在componentdidMount中设置的状态,为什么我的状态没有更新回我在componentdidMount中指定的状态 这是我的密码 class FilterInputs extends Component { constructor(props) { super(props); this.state = {
class FilterInputs extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.onSubmit = this.onSubmit.bind(this);
}
searchHandler(event) {
event.preventDefault();
let itemss = this.state.items;
let searcjQery = event.target.value.toLowerCase();
let x = itemss.filter(el => {
let searchValue = el.rocket.rocket_name.toLowerCase();
return searchValue.indexOf(searcjQery) !== -1;
})
this.setState({
items: x
});
}
componentDidMount() {
axios.get(`http://localhost:8001/api`).then(res => {
const missions = res.data;
missions.map(item => {
const xx = item.rocket.rocket_name;
});
this.setState({
items: missions
});
});
}
我可以知道我做错了什么吗?提前感谢您。让我们在状态中设置一个名为rocketNameQuery的过滤器,并基于该查询进行渲染
我修改了代码,使其更具可读性
class FilterInputs extends Component {
constructor(props) {
super(props);
this.state = {
missions: [],
// set our filter condition
rocketNameQuery: '',
};
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount() {
axios.get('http://localhost:8001/api')
// extract data to a variable named missions and set our state
.then(({ data: missions }) => {
this.setState({ missions });
});
}
searchHandler(event) {
event.preventDefault();
const rocketNameQuery = event.target.value.toLowerCase();
// update rocketNameQuery leaving state.missions untouched
this.setState({ rocketNameQuery });
}
checkFilterQuery(mission, rocketNameQuery) {
return mission.rocket.rocket_name.toLowerCase() === rocketNameQuery;
}
render() {
const { missions, rocketNameQuery} = this.state;
return !rocketNameQuery
? missions.map(mission => <div key={/* Add a unique key */}>{/* render logic */}</div>)
: (
<div>
// check if our item rocket name match our rocketNameQuery
{missions.map(mission => this.checkFilterQuery(mission, rocketNameQuery)
// match ? render logic
? <div key={/* Add a unique key */}>{/* Your render logic here */}</div>
// no match ? return null which will render nothing
: null
))}
</div>
);
}
}
您能显示componentDidUpdate的代码吗?您好@Simbathesaller,很抱歉,我键入的不是componentDidUpdate,而是componentDidMount。发生的情况是,当searchHandler运行时,您更改了状态,导致您丢失状态。最好添加一个searchQuery到state,这样我们可以基于searchQuery呈现我们的项目,保持state.items不变。不要修改你的真实来源,你的项目数组在你的状态。制作一份副本并将其用于筛选谢谢@Asaf Aviv,我已经尝试了你的代码它是有效的,但是有没有办法先渲染数据,然后再在其上进行筛选?@JohnWick基本上从所有任务开始=>用户筛选时筛选=>筛选为空时全部显示?