【问题标题】:react passing redux props to components反应将 redux 道具传递给组件
【发布时间】: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


【解决方案1】:

发生这种情况是因为您在渲染Avatar 组件之前没有等待来自fetchData 的数据。 由于componentDidMount 只被调用一次,因此在挂载时,您只在render 中看到“正确”的道具是有道理的。

目前没有办法解决这个问题,但将来当React Suspense 出现时,这将是一个轻微的非问题。

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2019-01-27
    • 1970-01-01
    • 2021-10-07
    • 2020-03-26
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多