简体   繁体   English

如何使props.relay.setVariables更新我的数据?

[英]How to make props.relay.setVariables update my data?

I'm trying to use a search component's 'onChange' to filter results using this.props.relay.setVariables but nothing gets re-rendered. 我正在尝试使用搜索组件的'onChange'使用this.props.relay.setVariables过滤结果,但没有任何内容被重新呈现。 I'm also hoping that when it does filter, that it will still use the Shuffle component. 我也希望当它进行过滤时,仍将使用Shuffle组件。 We are making one trip to the DB up front, and all these subsequent relay queries are coming from a cache (not sure if that is pertinent). 我们正在一次访问数据库,而所有这些后续中继查询都来自缓存(不确定是否相关)。

const GamesScreen = React.createClass({
  propTypes: {
    viewer: PropTypes.object,
  },
  search (e) {
    let searchStr = e.target.value;
    this.props.relay.setVariables ({ query: searchStr}, onFetch);
  },

  onFetch (){
    // does something need to happn in here to actually filter and re-render?
  },
  getSubjects ()
    {
    return this.props.viewer.subjects.edges;
  },
  render ()
    {
    const games = this.getSubjects().map(game => {
      return (
        <div className="Game-container" key={game.node.name}>
          <Game game={game.node} />
        </div>
      );
    });

    return (
      <div className="GamesScreen">
        <TopContainer>
          <TopBar viewer={this.props.viewer} />
        </TopContainer>
        <MidBar viewer={this.props.viewer} />
        <input type="search" placeholder="Search" onChange={this.search} />
        <div className="GamesScreen-container">
          <Shuffle duration={300} fade>
            {games}
          </Shuffle>
        </div>
      </div>
    );
  },
});

export default Relay.createContainer(GamesScreen, {
  initialVariables: {
    query: '',
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        subjects(query: "", first: 5)
         {
          edges {
            node {
              name
            }
          }
        },
        ${TopBar.getFragment('viewer')},
      }
    `,
  },
});

You just need to use the variable in your fragment. 您只需要在片段中使用变量。 In GraphQL, variables are used by prepending $ to the variable name, kinda like bash or whatever: 在GraphQL中,通过在变量名前加$来使用变量,有点像bash或其他名称:

export default Relay.createContainer(GamesScreen, {
  initialVariables: {
    query: '',
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        subjects(query: $query, first: 5) // <-- USE $query TO MODIFY FRAGMENT AT RUNTIME
         {
          edges {
            node {
              name
            }
          }
        },
        ${TopBar.getFragment('viewer')},
      }
    `,
  },
});

For more details, see the docs about Relay Containers and variables here 有关更多详细信息,请参见此处的有关中继容器和变量的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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