我正在尝试通过反应路由器,链接将道具传递给子组件。当我重新加载页面时,控制台日志记录了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>
)
}
}
下面是我要显示数据的组件,它似乎正在渲染3次
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>
)
}
}
答案 0 :(得分:2)
您不应在构造函数中执行setState
。而是使用此类道具初始化状态。
class CoinInfo extends React.Component{
constructor(props){
super(props)
this.state={
data: props
}
}
}
此外,您似乎甚至不需要本地状态,也可以在渲染函数中直接使用this.props.data
。
答案 1 :(得分:0)
由于您正在通过链接发送状态,因此能够通过链接发送数据,并通过将其放入路由对象中来访问它,例如:this.props.location.state
。