简体   繁体   English

通过搜索传递道具,不会设置状态

[英]Passing props from search, Won't setState

I made a search component, I am passing the results of the search back to the parent using props. 我做了一个搜索组件,我正在使用道具将搜索结果传递回父级。 The issue is it will not setState until the function is triggered so I get the error of undefined in the map loop. 问题是,直到函数被触发,它才会setState,因此我在映射循环中得到未定义的错误。

I am trying to show all results until the search is triggered using onChange. 我试图显示所有结果,直到使用onChange触发搜索为止。

How can I accomplish this. 我该怎么做。

//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>

          );
        }

Always check for empty or null while running map over array. 在数组上运行映射时,请始终检查是否为空或null。

userSearch && userSearch.map(item => {
 console.log(item);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM