我试图通过 react 路由器将 Prop 传递给子组件,链接。当我重新加载页面时,控制台记录3次,第一个日志未定义,第二个日志显示我需要的数据,第三个日志再次显示未定义.我做错了什么?
这个组件是我进行外部 API 调用并获取数据的地方,然后将其存储到状态
class CryptoList extends React.Component {
constructor(props) {
super(props)
this.state = {
data: {}
}
}
componentDidMount = async () => {
await this.coinCall()
}
coinCall = async () => {
try {
const data = await ApiData()
this.setState({
data: data
})
}
catch (error) {
throw error
}
}
render() {
const coinsArray = Array.from(this.state.data)
const coins = coinsArray.map(coin => (
<div><Link
key={coin.id}
to={{
pathname: `/ CoinInfo`,
state: { data: coin.name, }
}}
>
<Coin
pathname={CoinInfo}
render={CoinInfo}
coinId={coin.name}
price={coin.market_data.current_price.usd}
image={coin.image.small}
/>
</Link>
</div>
))
return (
<div>
<ul>{coins}</ul>
</div>
)
}
}
下面是我想要显示数据的组件,它似乎渲染了三次
class CoinInfo extends React.Component {
constructor(props) {
super(props)
this.state = {
data: []
}
this.setState({ data: props })
}
componentDidUpdate() {
let data = this.state.data
console.log("$$$", this.props)
return (<div>{data}</div>)
}
render() {
console.log("**********", this.props.data)
return (
<div>
<p>working</p>
</div>
)
}
}
最佳答案
您不应该在构造函数中执行setState
。相反,使用这样的 props 初始化状态。
class CoinInfo extends React.Component{
constructor(props){
super(props)
this.state={
data: props
}
}
}
而且看起来你甚至不需要本地状态,你可以直接在渲染函数中使用 this.props.data
。
关于javascript - 没有立即收到 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512126/