gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:51:31 24 4
gpt4 key购买 nike

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

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 组件在数据库中搜索数据时,它会获取并加载正确的数据,这太棒了。但是,如何将这个"new"找到的数据传递给 CarList 组件,以便在页面上显示?

最佳答案

我会做的是:

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 ...
)
}

关于javascript - ReactJS - 将数据从子组件传递到其父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52133076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com