Reactjs 在渲染前设置状态
我有Reactjs 在渲染前设置状态,reactjs,Reactjs,我有App.js,里面有一个组件。将其命名为示例。我想用App.states设置示例的道具。例如,example有一些道具:name,id。在App中,我想从服务器获取我想要的数据,并将其设置为App的状态,然后在App呈现之前将其分配给示例的道具。这里的问题是我读到了关于组件willmount(),但是React文档说这不是最好的方法。那么,最好的方法是什么呢?一般的方法是将ajax响应存储在应用程序中,当响应保存到状态时,使用从响应中获取的数据呈现示例组件 class App extends
App.js
,里面有一个组件。将其命名为示例
。我想用App.state
s设置示例的道具。例如,example
有一些道具:name
,id
。在App
中,我想从服务器获取我想要的数据,并将其设置为App
的状态,然后在App呈现之前将其分配给示例的道具。这里的问题是我读到了关于组件willmount()
,但是React文档说这不是最好的方法。那么,最好的方法是什么呢?一般的方法是将ajax响应
存储在应用程序
中,当响应保存到状态时,使用从响应中获取的数据呈现示例
组件
class App extends React.Component
state = { response: null }
componentDidMount() {
runYouFetchHere
.then((response) => this.setState({ response }))
}
render() {
const { response } = this.state
if (response === null) { return null }
return (
<Example name={response.name} id={response.id} />
)
}
}
类应用程序扩展了React.Component
状态={响应:null}
componentDidMount(){
runYouFetchHere
.then((response)=>this.setState({response}))
}
render(){
const{response}=this.state
if(response==null){return null}
返回(
)
}
}
当react组件中有更新时,将调用以下任何更新方法
试图在内部设置状态
componentWillRecieveProps(){
this.setState({ })
}
你也需要写代码。这将有助于人们理解您的问题所在。Thx,但是示例中的语法键入component将接收props
,而不是component将接收props
嘿,谢谢您的信息员!。但我认为它现在已经被弃用了。所以,我们从道具中获取了DerivedStates。代替这个。