ReactJS-将数据从子组件传递到其父组件

时间:2018-09-02 00:13:55

标签: javascript reactjs jsx

我在应用程序中具有以下组件结构:

class Car extends Component {
    constructor() {
        super();
        this.state = {
            cars: [],
            ...
        }
    }
    componentDidMount() {
        axios.get('/api/cars')
            .then((response) => {
                this.setState({cars: response.data});
                console.log('cars: ', cars);
            }).catch(err => {
                console.log('CAUGHT IT! -> ', err);
            });
    }
    render() {
      return (
        ...
        <CarAddNew />
        <CarSearch />
        <CarList cars={this.state.cars} />
      )
    }
}

然后

export default class CarSearch extends Component {
    constructor(){...}
    handleSearchSubmit(e) {
        e.preventDefault();
        ..
        axios.post('/api/cars/search', searchCars)
            .then(response => {
                console.log('response.data: ', response.data);
            })
    }
    render() {
        return(
          ... search form ...
        )
    }

当我通过CarSearch组件在数据库中搜索数据时,它将获取并加载正确的数据,这很棒。但是,如何将找到的这些“新”数据传递给CarList组件,以便可以在页面上显示?

2 个答案:

答案 0 :(得分:4)

我要做的是以下事情:

class Car extends Component {
    constructor() {
        super();
        this.state = {
            cars: [],
            ...
        }
    }
    componentDidMount() {
        axios.get('/api/cars')
            .then((response) => {
                this.setState({cars: response.data});
                console.log('cars: ', cars);
            }).catch(err => {
                console.log('CAUGHT IT! -> ', err);
            });
    }
    handleSearch = () => {
        axios.post('/api/cars/search', searchCars)  // not sure where you are getting searchCars from, but you should get the idea
            .then(response => {
                this.setState({cars: response.data})
                console.log('response.data: ', response.data);
            })
    }

    render() {
      return (
        ...
        <CarAddNew />
        <CarSearch onSearch={this.handleSearch} />
        <CarList cars={this.state.cars} />
      )
    }
}


export default class CarSearch extends Component {
    constructor(){...}
    handleSearchSubmit(e) {
        e.preventDefault();
        this.props.onSearch() // I'm assuming you probably want to pass something here
    }
    render() {
        return(
          ... search form ...
        )
    }

答案 1 :(得分:2)

一种选择是通过CarSearch上的道具向上传播数据。考虑(截断)示例...

handleSearchSubmit(e) {
  e.preventDefault();
  axios.post('/api/cars/search', searchCars).then(response => {
    this.props.onData(response.data);
  });
}

其中,onData回调到以下内容(随后为设置状态)...

constructor() {
  // [...]
  this.onSearchResult = this.onSearchResult.bind(this);
}

onSearchResult(cars) {
  this.setState({cars}); // results from CarSearch
}

render() {
  return (
    <CarAddNew />
    <CarSearch 
      onData={this.onSearchResult} />
    <CarList 
      cars={this.state.cars} />
  )
}
相关问题