Javascript 在react中渲染后使用GetOffsetSight和异步数据
下面的代码很简单,但在我看来不恰当也可以。基本上,我试图计算列表的高度。但是有什么比设置超时黑客更好的解决方案呢?我尝试了componentDidMount,但这不能保证数据已加载Javascript 在react中渲染后使用GetOffsetSight和异步数据,javascript,reactjs,Javascript,Reactjs,下面的代码很简单,但在我看来不恰当也可以。基本上,我试图计算列表的高度。但是有什么比设置超时黑客更好的解决方案呢?我尝试了componentDidMount,但这不能保证数据已加载 class App extends Component { constructor() { super(); this.state = { users: null }; } componentWillMount() { axios.get("https://
class App extends Component {
constructor() {
super();
this.state = {
users: null
};
}
componentWillMount() {
axios.get("https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")
.then(response => this.setState({ users: response.data }));
}
componentDidMount() {
setTimeout(() => {
console.log(this.userElem.offsetHeight);
}, 1000);
}
render() {
return (
<div style={styles}>
<div ref={elem => (this.userElem = elem)}>
{this.state.users &&
this.state.users.map(o =>
<p>
{o.first}
</p>
)}
</div>
</div>
);
}
}
类应用程序扩展组件{
构造函数(){
超级();
此.state={
用户:空
};
}
组件willmount(){
axios.get(“https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")
.then(response=>this.setState({users:response.data}));
}
componentDidMount(){
设置超时(()=>{
console.log(this.userElem.offsetHeight);
}, 1000);
}
render(){
返回(
(this.userElem=elem)}>
{this.state.users&&
this.state.users.map(o=>
{o.first}
)}
);
}
}
演示您可以在那里使用并检查this.userElem.offsetHeight变量。此外,我还将使用componentDidMount更改componentWillMount。您可以阅读更多信息。不要在内部调用api,而是在方法内部调用DoIt,并使用回调方法检查元素高度 像这样:
componentDidMount() {
axios.get("https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")
.then(response => {
this.setState({ users: response.data }, () => {
console.log(this.userElem.offsetHeight);
})
});
}
或者您也可以使用方法,它在更新发生后立即被调用。初始呈现时不调用此方法。文章claim componentWillMount的行为与构造函数相同,那么为什么还有componentWillMount?这是干什么用的?大多数时候你不需要componentWillMount,但是你可以根据初始的道具在里面设置state,而不是在构造函数中这样做。state={}不会触发另一个呈现调用。componentWillMount的行为和构造函数一样,那么为什么还有componentWillMount呢?这是干什么用的?它在服务器端渲染中扮演着非常重要的角色:这是唯一一个在服务器端渲染中调用的生命周期挂钩。通常,我们建议改为使用构造函数()。我使用了componentDidUpdate。