正如标题所说,我正在尝试从子组件调用放置在父组件中的方法(componentDidMount) -我的应用程序中有以下组件结构:
export default class Today extends Component {
constructor(props) {
super(props);
this.state = {
stats: [],
loading: true
};
}
componentDidMount() {
axios.get(api_url)
.then((res) => {
console.log('res.data');
this.setState({
stats: res.data,
loading: false
});
})
}
render() {
return (
<Stats loading={this.state.loading} stats={this.state.stats} />
);
}
}
和
export default class Stats extends Component {
constructor(props) {
super(props);
}
onRefresh() {
alert('X');
// here I need to refresh the data in 'this.props.stats'
// and re-display it (fresh data)
}
render() {
const {loading, stats} = this.props;
if (loading) {
return (
<Text>Loading...</Text>
);
} else {
return (
<Container>
<Content refreshControl={
<RefreshControl
onRefresh={this.onRefresh.bind(this)}
/>
}>
...
但是如何从Stats
组件重新调用Today -> componentDidMount
中的代码呢?
提前谢谢你
发布于 2018-07-31 06:48:13
您的Stats
组件需要接受一个额外的属性onRefresh
,并将其传递给RefreshControl
组件。然后,父进程可以通过调用axios请求的prop提供一个处理程序:
class Today extends Component {
// ...
componentDidMount() {
this.fetchData();
}
fetchData = () => {
axios.get(api_url)
.then((res) => {
console.log('res.data');
this.setState({
stats: res.data,
loading: false
});
})
}
// handle a refresh by re-fetching
handleRefresh = () => this.fetchData();
render() {
return (
<Stats
loading={this.state.loading}
stats={this.state.stats}
onRefresh={this.handleRefresh}
/>
);
}
}
和
class Stats extends Component {
render() {
const {loading, stats, onRefresh} = this.props;
if (loading) {
return (
<Text>Loading...</Text>
);
} else {
return (
<Container>
<Content refreshControl={
<RefreshControl
onRefresh={onRefresh}
/>
}>
...
https://stackoverflow.com/questions/51603199
复制相似问题