简体   繁体   English

对传递的redux道具进行反应

[英]react passing redux props to components

Within this Avatar component, I want to set the state to match the props before it renders but the component only seems to update with the correct props in its render function. 在此Avatar组件中,我想设置状态以使其与渲染之前的props匹配,但该组件似乎仅使用其render函数中的正确props进行更新。

eg. 例如。

main component gets data on its componentDidMount, passes that data to another component (Avatar), Avatar sets the state's data to match the passed data, UI renders with that data. 主组件在其componentDidMount上获取数据,然后将该数据传递给另一个组件(Avatar),Avatar设置状态数据以匹配传递的数据,UI将该数据呈现。

by default the redux store has avatar as avatar.png 默认情况下,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"}

This happens because you're not waiting for the data from fetchData before rendering your Avatar component. 发生这种情况是因为您在呈现Avatar组件之前不等待fetchData的数据。 Since componentDidMount is only called once, on mount, it makes sense that you're only seeing your "correct" props in render . 由于componentDidMount在挂载时仅被调用一次,因此有意义的是,您只能在render看到“正确的”道具。

Currently there is no way around this but in the future when React Suspense comes out this will be a slight non-issue. 当前无法解决此问题,但是将来当React Suspense出现时,这将是一个小问题。

Until we get the new shiny async features from React, I'd suggest creating a new variable in your store that you can set accordingly before and after your fetchData action completes and use it in your render method 在我们从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM