Reactjs 在渲染中运行不带事件的函数
我是ReactJS新手,想问一下这里的函数是如何工作的。我有这样一个类、函数和渲染:Reactjs 在渲染中运行不带事件的函数,reactjs,Reactjs,我是ReactJS新手,想问一下这里的函数是如何工作的。我有这样一个类、函数和渲染: class MainTable extends React.Component { constructor(props) { super(props); this.state = { results: [] }; this.getREST = this.getREST.bind(this); } getREST() { console.log(th
class MainTable extends React.Component {
constructor(props) {
super(props);
this.state = {
results: []
};
this.getREST = this.getREST.bind(this);
}
getREST() {
console.log(this.props.str)
axios.get(this.props.str)
.then(res => {
const results = res.data.results.map(obj => obj);
this.setState({results});
});
console.log(this.state.results);
}
render() {
return (
<Table hover striped bordered hover responsive size="sm">
<thead>
<tr>
<th>Name</th>
<th>Name</th>
<th>Name</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{this.state.results.map(result =>
<tr key={result.Name}>
<td>{result.Name}</td>
<td>{result.Name}</td>
<td>{result.Name}</td>
<td>{result.Name}</td>
</tr>
)}
</tbody>
</Table>
);
}
}
但是如何在没有任何事件的情况下运行
getRest()
函数,只在render()
中?您应该在componentDidMount
生命周期方法中获取数据,而不是在render
中
componentDidMount(){
axios.get(this.props.str)
.then(res => {
const results = res.data.results.map(obj => obj);
this.setState({results});
});
}
如果你必须渲染它,为什么你还需要一个函数呢?只需在渲染块中编写代码。最好是在componentdidmount中编写axios,而不是使用任何函数。这不像在渲染中,我会有一个无限循环?我只需要运行一次。循环,因为您在这里使用
setState
,它一次又一次地调用re render
和另一个setState。。。检查我的回答如果你需要运行一次,那么就像我上面说的那样,在componentdimount中编写axios。这是一个预定义的方法,在你的组件刚刚渲染完成后会自动被调用,伙计们。我明白了,答案是ty。我想,map
在这里不是必需的:this.setState({results:res.data.results})代码>:)@MayankShukla,谢谢
componentDidMount(){
axios.get(this.props.str)
.then(res => {
const results = res.data.results.map(obj => obj);
this.setState({results});
});
}