[英]react passing redux props to components
在此Avatar組件中,我想設置狀態以使其與渲染之前的props匹配,但該組件似乎僅使用其render函數中的正確props進行更新。
例如。
主組件在其componentDidMount上獲取數據,然后將該數據傳遞給另一個組件(Avatar),Avatar設置狀態數據以匹配傳遞的數據,UI將該數據呈現。
默認情況下,redux存儲的化身為avatar.png
class Account extends React.Component {
componentDidMount() {
this.props.fetchData();
}
render() {
const { data } = this.props
return(
<Switch>
<Route path="/avatar" exact={true} render={() => (<Avatar {...data} />)} />
</Switch>
)
}
}
class Avatar extends React.Component {
constructor(props) {
super(props)
console.log('constructor', this.props)
this.state = {}
}
componentDidMount() {
console.log('componentDidMount', this.props)
// this.setState({ data: this.props.data })
}
render() {
console.log('render', this.props)
return null
}
}
constructor {avatar: "avatar.png"}
test.js:62 render {avatar: "avatar.png"}
test.js:58 componentDidMount {avatar: "avatar.png"}
test.js:62 render {avatar: "something.png", other: "stuff"}
發生這種情況是因為您在呈現Avatar
組件之前不等待fetchData
的數據。 由於componentDidMount
在掛載時僅被調用一次,因此有意義的是,您只能在render
看到“正確的”道具。
當前無法解決此問題,但是將來當React Suspense出現時,這將是一個小問題。
在我們從React獲得新的閃亮異步功能之前,我建議您在商店中創建一個新變量,您可以在fetchData操作完成之前和之后進行相應設置並將其用於渲染方法中
class Account extends React.Component {
componentDidMount() {
this.props.fetchData();
}
render() {
const { data, loadingComplete } = this.props
return (
loadingComplete === true
? <Switch>
<Route exact path="/avatar" render={() => (<Avatar {...data} />)} />
</Switch>
: 'Loading'
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.