我正在尝试实现一个搜索框,该搜索框将过滤来自其余端点的项目,但我无法理解如何保持列表的第一个状态,因为如果搜索框为空,我需要它返回它。 . 我用 this.props.someItem 尝试了很多例子,但我总是在控制台 TypeException 中得到错误,我读到了关于父子组件的信息,但没有运气。我试图让一个子组件执行查询并获取数据,但后来我没能把它放到父类中,我试过“this.state = { foo[] : foo2 }”; 不工作我试过直接分配它 foo = this.props.foo2; 再次没有运气我得到了 TypeError。对不起,这可能是一个简单的问题,但我对 js 和反应很陌生。提前感谢您的任何帮助。
class About extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
this.handleChange = this.handleChange.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
items: nextProps.model
});
}
componentDidMount() {
fetch('something/')
.then(res => res.json())
.then((result) => {
this.setState({
items: result
});
}
)
}
我有一个函数 handleChange(e) => { }; 如何获得“items”数组的初始状态?filteredList = this.props.items - 我试过这个它给我错误 TypeError: undefined ans 也是如果我改变状态它没问题但原始数据丢失我想问一下每次获取数据是否是一个好习惯如果例如,查询包括此视图的全部数据。
试试这个:
class About extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
filteredItems: []
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
fetch('something/')
.then(res => res.json())
.then((result) => {
this.setState({
items: result
//Note: You can set filteredItems here to result as well
//if you want it to start out unfiltered
});
}
)
}
handleChange(evt) {
const baseItems = this.state.items;
//Your filtering logic here
this.setState({ filteredItems: yourFilteredArray });
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句