我的 react 很天真,我正在努力处理一些简单的事情,需要你的帮助。 我需要做的就是将外部服务的值数组作为 Prop 传递给另一个服务
方法
render() {
let todolist="default";
axios.get('http://localhost:8888/todoitems').then(function(res){
todolist=res.data;
});
return (
<div className="App">
<input type="text" ref="newvalue"/>
<button onClick={this.save}>Submit</button>
<TodoList data={todolist} />
</div>
);
}
发生的情况是,“默认”获取为 this.props.data,而不是来自外部服务的响应。
此外,我得到“当我尝试设置为状态时,无法设置未定义的属性“状态”。如下所示:
constructor(props){
super(props);
axios.get('http://localhost:8888/todoitems').then(function(res){
this.state={
data:res.data;
}
});
}
请帮忙。
最佳答案
您的 API 请求不应出现在渲染方法中,因为每次组件更新时,都会调用渲染方法,因此会再次发出 API 请求。您应该在 componentDidMount
生命周期方法中发出 API 请求,然后使用可在 render 方法中使用的响应更新状态。如果您需要定期触发 API 请求,请将其放入 setInterval
方法中。附:不要忘记清除 componentWillUnmount
函数中的间隔计时器
state = {
todoList: "default"
}
componentDidMount() {
axios.get('http://localhost:8888/todoitems').then((res) => {
this.setState({todolist: res.data})
});
}
render() {
return (
<div className="App">
<input type="text" ref="newvalue"/>
<button onClick={this.save}>Submit</button>
<TodoList data={this.state.todolist} />
</div>
);
}
关于javascript - 使用 axios 获取数据并作为 props 导出到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969932/