javascript - ReactJS/GraphQL : Call query from submit button

标签 javascript reactjs graphql-js

当我的应用程序加载时,下面的查询将运行,数据库的结果将显示在浏览器中。但是,我的应用程序还有一个提交按钮。当按下提交按钮并传递来自提交的时间戳输入时,如何运行整个组件?

handleSubmit(event) {
  event.preventDefault();
  console.log(this.state.inputValue)
  this.state = {
    inputValue: new Date(document.getElementById("time").value).valueOf()
  };
  console.log(this.state);            
}

这是UserList组件代码:

const UserList = props => (
  <Query
    query={gql`
      query action($timestamp: Float!) {
        action(timestamp: $timestamp) {
          action
          timestamp
          object {
            filename
          }
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error</p>;

      return (
        <Item.Group divided>
          {data.action.map(action => (
            <div>
              <ul>
                <li>{action.action}</li>
                <li>{action.timestamp}</li>
                <ul>
                  {action.object.map(obj => {
                    return <li>{obj.filename}</li>;
                  })}
                </ul>
              </ul>
            </div>
          ))}
        </Item.Group>
      );
    }}
  </Query>
);

export default UserList;

最佳答案

父组件包含提交按钮和生存状态。提交处理程序应该只使用 ... setState() 设置状态值 - 不直接!

如果没有默认状态/值,请使用条件渲染...在状态(时间戳)未定义时,在父渲染中显示一些占位符。如果值存在,则将其作为 prop 传递:

{!this.state.inputValue ? <SomePlaceholder />
: <UserList timestamp={this.state.inputValue} />}
// place input, submit button where you want (after/before results)

UserList 将使用 props 进行调用 - 'props.timestamp' 可以在 graphql 查询文字中使用。

当输入再次更改时,提交处理程序将更改父级状态,并且该更改将作为属性再次传递给子级,触发查询,重新呈现结果。

关于javascript - ReactJS/GraphQL : Call query from submit button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641342/

相关文章:

javascript - 带有缩放和选择事件的谷歌图表线

reactjs - 如何运行 React 应用程序的构建?

javascript - React Router - 未加载新组件

javascript - 表达式 "Something"? "Something": "Something else" shorter?

graphql - 我为什么要在 GraphQL 结果中取回查询名称?

graphql - 枚举可以在 GraphQL 中返回描述(字符串)吗?

node.js - GraphQL - 向 ObjectType 传递参数

javascript - 如何在同一行中对齐图例标记中的三个元素?

javascript - meteor 的 json 查看器

javascript - 恢复第一个单选按钮选中的 onclick 事件