2017-10-05 61 views
0

我有一個Graphcool後端,我想通過按鈕時搜索。據我的理解:如果我使用react-apollo中的graphql容器,組件將在安裝後立即進行查詢。用client.query的響應更新商店與react-apollo爲一個seachbar函數

這不是我想要的。我打算僅在按下按鈕時進行搜索。我知道,withApollo容器允許我做一個查詢,像這樣:

this.props.client.query({ 
     query: MY_QUERY, 
     variables: { 
      first, // for pagination 
      skip, 
      orderBy, 
      searchText 
     } 
    }); // returns a promise 

我的問題:我如何更新它返回響應的店嗎?我是否以這種錯誤的方式去做?

回答

2

所以我意識到我正在走這個錯誤的路。我發現這個有用的帖子:search feature with react-apollo

我會更簡單有狀態,然後更新所述狀態,象這樣的迴應:

this.props.client.query({ 
    query: MY_QUERY, 
    variables: { 
     first, // for pagination 
     skip, 
     orderBy, 
     searchText 
    }, 
}).then(result => this.setState({ thingsToRender: result.data.thingsToRender }); 

那麼你當然會呈現由映射對象在它或使用FlatList(如果你使用反應原生)。

我也發現如何更新我的店面,如果我真的想這樣做。該組件將需要由雙方graphqlwithApollo高階組件從react-apollo包裹這個工作:

compose(
    withApollo, 
    graphql(SOME_QUERY) 
)(MyComponent) 

你再做出這樣的方法使:

onSearchButtonPress = async() => { 
    const { first, skip, orderBy, searchText } = this.state; 

    const result = await this.props.client.query({ 
    query: MY_QUERY, 
    variables: { 
     first, 
     skip, 
     orderBy, 
     searchText 
    } 
    }); 
    const items = result.data.items; 
    this.props.data.updateQuery(prev => ({ 
    ...prev, 
    allItems: _.uniqBy([...prev.allItems, ...items], o => o.id) 
    // lodash uniqBy helper method helps with removing older items 
    // with the same id (essentially updating them) 
    }); 

這幾乎就像更新狀態在減速機中。