我正在开发一个简单的网站,它使用 React 将来自 API(JSON)的数据显示到页面中。
我正在使用 fetch() API。
我能够从 API 获取数据并将其设置为“应用程序”组件状态,但无法将其传递给我手动创建的表和行组件。
class App extends React.Component {
constructor (props) {
super(props)
this.state = {ticker: {}, volume: {}}
this.loadData = this.loadData.bind(this)
this.loadData()
}
loadData () {
fetch(ticker)
.then((resp) => resp.json())
.then((data) => {
this.setState({
ticker: data
})
})
.catch((err) => {
console.log(err)
})
fetch(volume)
.then((resp) => resp.json())
.then((data) => {
this.setState({
volume: data
})
})
.catch((err) => {
console.log(err)
})
}
render () {
return (
<div>
<Navbar />
<div className='container'>
<div className='align'>
<div className='element' />
</div>
<Table volume={this.state.volume} ticker={this.state.ticker} />
</div>
</div>
)
}
}
底线: 我有一个包含数据的 API,并且有 3 个组件,即表,其中还有一个行组件。 我想在 Row 组件中显示变量 看起来像这样
<Row img='eth' name='Ethereum' price='' volume='' change='' marketCap='' />
最佳答案
你的构造函数:
constructor (props) {
super(props);
this.state = {ticker: {}, volume: {}}
this.loadData = this.loadData.bind(this);
}
为了获取数据,您始终需要使用生命周期组件,例如 componentDidMount
或 componentWillMount
,因此:
componentDidMount(){
this.loadData()
}
然后在您所在的州您将获得数据。
在您的 render
方法中将其作为 props 传递给 Table
组件:
render(){
return(
<Table volume={this.state.volume} ticker={this.state.ticker} />
)
}
然后从 Table
组件将其作为 props 传递给 Row
组件,因此:
render(){
return(
<Row img='eth' name='Ethereum' price='' volume={this.props.volume} change='' marketCap='' />
)
}
如果您有对象数组,例如:
this.state = {
volume: [ {name: "One", size: 1 }, {name: "Two", size: 2 }, ..... ]
}
您需要循环遍历数组并显示每个对象的 Row
组件。
因此,您的 Table
组件应如下所示:
render(){
return (
<div>{this.props.volume.map(vol => <Row img='eth' name='Ethereum' price='' volume={vol} change='' marketCap='' />) }</div>
)
}
关于reactjs - 使用 React 显示来自 fetch api 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44710304/