use*_*090 1 javascript reactjs react-native
正如标题所说,我试图从子组件调用放置在父组件中的方法 (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} />
);
}
}
Run Code Online (Sandbox Code Playgroud)
和
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)}
/>
}>
...
Run Code Online (Sandbox Code Playgroud)
但是如何Today -> componentDidMount从Stats组件中重新调用代码?
先感谢您
你的Stats组件需要接受一个额外的 proponRefresh传递给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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
和
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}
/>
}>
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5220 次 |
| 最近记录: |