当您依赖异步方法时如何渲染反应

时间:2018-11-08 16:19:15

标签: reactjs react-router-v4

我是新来的反应者,但是我进步了一点,并且遇到了一个我不知道如何在代码中表达自己想要的东西的问题:

我的路由上有一个“代理”,可将信息从url保存到阿波罗缓存中

function saveUrlVarsToCache(props) {
    const LOCAL_CACHE = gql`
            query localCache {
                kind @client
                name @client
                eid @client
                issueId @client
                view @client
            }
        `

    const {match} = props
    // console.log( "Match path: ", match.path )


    return (
            <Query query={LOCAL_CACHE}>
                { /***async***/ ({data, client}) => {
                    const matchParams = {...(props.match.params), ...{view: Views.findViewByPath(match.path).name}}

                    //only override if the user types the url manually
                    if (data.name)
                        delete matchParams.name
                    console.log("Writing route params to local cache ", matchParams)
                    /***await***/ client.writeData({data: matchParams})
                    return <MainComp {...props}/>
                }}
            </Query>)
}

我在每条经过的路线中都调用此方法

<Route exact path="/:kind"
                                         render={saveUrlVarsToCache}>

我的问题是,comp在apollo方法client.writeData完成之前显示。

我不能将return comp语句放在then子句中,因为它将返回then方法而不是saveUrlVarsToCache。

奇怪的是,即使使用async await语法(在此处评论),我也会收到错误消息:

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in Query (at App.js:54)
    in Route (at App.js:88)
    in Switch (at App.js:74)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:73)

由于我需要道具,因此无法在componentWillMount生命周期方法中调用此方法...

该怎么办?

p.s:我肯定可以通过在缓存保存的then子句中调用人工setState({})来重新渲染,但这会触发我不希望的其他render()调用

p.p.s:也许有一个库,但我不知道他们在后台做什么,所以我现在避免这样做:github.com/capaj/react-promise

1 个答案:

答案 0 :(得分:0)

class MainComponent extends React.Component {
  async componentDidMount()=>{
  /*call async foo here and set state*/
  }
  render() {
    return (
      <>
        <Route exact path="/:kind" 
          render={<MainComp component_prop={this.state.something} />} 
        />
      </>
    )
  }
}

尝试这样

相关问题