【发布时间】:2018-09-05 17:53:50
【问题描述】:
我有两个组件用于获取和呈现数据。我想要做的是在单击时更改CarSearch 组件中该按钮的标签(理想情况下也是 CSS),当搜索完成时,我想将基本的“搜索”标签放在那里。
但是,当我单击搜索按钮并完成搜索时,未设置“搜索”标签,并且保留在那里的标签仍然是“正在过滤...”。现在有什么变化?
也许我只是把它复杂化了,有更好的方法来实现它。
class Car extends Component {
constructor() {
super();
this.state = {
cars: [],
searchBtn: 'Searchh'
}
}
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)
.then(response => {
this.setState({cars: response.data, searchBtn: 'Seach'}) // however, this `searchBtn` will not be passed to `CarSeach`
console.log('response.data: ', response.data);
})
}
render() {
return (
...
<CarAddNew />
<CarSearch
onSearch={this.handleSearch}
searchBtnLabel={this.state.searchBtn}
/>
<CarList cars={this.state.cars} />
)
}
}
export default class CarSearch extends Component {
constructor(props){
super(props);
searchBtn: props.searchBtnLabel
}
handleSearchSubmit(e) {
e.preventDefault();
this.setState({ searchBtn: 'Filtering...'});
this.props.onSearch(...)
}
render() {
return(
... search form ...
<button type="submit" className="btn btn-primary btn-sm mx-sm-2">
{this.state.searchBtn}
</button>
)
}
【问题讨论】:
标签: reactjs state react-props