我是新手,但我有点进步,我面临一个问题,我不知道如何在代码中表达我想要的:
我的路线上有一个“代理”,可以将信息从url保存到apollo缓存
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 method 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