javascript - 从搜索中传递道具,不会设置状态
问题描述
我制作了一个搜索组件,我正在使用道具将搜索结果传递回父级。问题是在触发函数之前它不会设置状态,所以我在地图循环中得到未定义的错误。
我试图显示所有结果,直到使用 onChange 触发搜索。
我怎样才能做到这一点。
//Search Component
export default class Searchbar extends Component {
constructor(props){
super(props)
}
state = {
input : '',
visable:[],
}
onChange=(e)=>{
this.setState({input: e.target.value})
let clone = [...this.props.theGitUsers]
if(e.value === ''){
this.setState({visable:clone})
}else{
let filteredSearch = clone.filter((loginUsers)=>{
return loginUsers.login.toUpperCase().includes(this.state.input.toUpperCase())
})
this.setState({visable:filteredSearch})
}
//Passing the state results to App Component using this props to the App function function
this.props.searchRes(this.state.visable);
}
render() {
return (
<div>
<input type="text" onChange= {this.onChange} value={this.state.input} />
</div>
)
}
}
//App.js Parent ////////////////////////
state={
gitusers:[],
searched:[],
loading:false,
}
componentDidMount(){
this.setState({loading:true});
setTimeout(() => {
axios.get('https://api.github.com/users')
.then(res=> this.setState({gitusers:res.data , loading:false}))
}, 1000);
}
//The search results from Searchbar Component
searchRes=(visable)=>{
this.setState({searched:visable})
}
render(){
return (
<div>
<Navbar title="Github Finder" icons="fab fa-github" />
<Searchbar theGitUsers = {this.state.gitusers} searchRes = {this.searchRes} />
<div className = "container">
<TheUsers gituser = {this.state.gitusers} loading={this.state.loading} />
</div>
</div>
);
}
解决方案
在数组上运行 map 时始终检查空或 null。
userSearch && userSearch.map(item => {
console.log(item);
});
推荐阅读
- php - 如何在 Laravel 中为请求发送多个响应?
- model-view-controller - 控制器方法不存在。但实际上是存在的。不通过请求传递值
- coq - 在 Coq 中如何划分两个 Nat?
- c++ - is there any way to partial instance a c++ template
- php - 将行移动到另一个表并插入其他值
- c# - 带任务的异步/等待,重构方法
- asp.net - MVC 项目中的 aspx 页面未读取 web.config
- reactjs - 当用户登录反应时,我需要更改登录以添加到购物车
- amazon-web-services - 向特定实例授予所有服务权限的 AWS IAM 策略
- linux - systemtap 中 .function() 和 .function().call 之间的区别