【发布时间】:2018-04-19 18:13:12
【问题描述】:
在这个 Avatar 组件中,我想在渲染之前设置状态以匹配道具,但该组件似乎只在其渲染函数中使用正确的道具进行更新。
例如。
主组件在其 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"}
【问题讨论】:
-
可能想研究一下使用 redux-thunk
-
我正在使用 redux-thunk,可能不正确
标签: reactjs