首页 > 解决方案 > 从搜索中传递道具,不会设置状态

问题描述

我制作了一个搜索组件,我正在使用道具将搜索结果传递回父级。问题是在触发函数之前它不会设置状态,所以我在地图循环中得到未定义的错误。

我试图显示所有结果,直到使用 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>

          );
        }

标签: javascriptreactjs

解决方案


在数组上运行 map 时始终检查空或 null。

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

推荐阅读