首页 > 解决方案 > Reacjs/Graphql:传递变量值以从事件中查询

问题描述

所以下面的代码正在更新 inputValue 的状态,但由于某种原因,该值没有被传递给查询,因为显示了以下错误:

[GraphQL 错误]:消息:所需类型“Float!”的变量“$timestamp” 未提供。,位置:[object Object],路径:未定义

所以我的问题是如何将 inputValue 分配给时间戳并将时间戳传递给 getObjectsQuery?

class Calendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ""
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit = event => {
    event.preventDefault();

    console.log(this.state.inputValue);
    this.setState({
      inputValue: new Date(document.getElementById("time").value).valueOf()
    }); //Parent component contains submit button and there lives state. Submit handler should only set value in state with...setState()- NOT directly
    this.props.data.refetch({
      //For some reason
      timestamp: this.state.inputvalue
    });

    console.log(this.state.inputValue);
  };

  render() {
    console.log(this.props);
    return (
      <div className="Calendar">
        <form onSubmit={this.handleSubmit.bind(this)}>
          <label>Date/Time</label>
          <input type="datetime-local" id="time" step="1" />
          <input type="submit" value="Submit" />
        </form>
      </div>
      //{this.render(){return (<UserList />)};
    );
  }
}

export default graphql(getObjectsQuery, {
  options: props => ({
    variables: {
      timestamp: props.inputvalue
    }
  })
})(Calendar);

标签: reactjsgraphqlreact-apollo

解决方案


我知道它已经在另一个地方解决了Reactjs/Graphql: TypeError: Object(...) is not a function

只是要记住(因为你还没有学会):

handleSubmit = event => {
  event.preventDefault();

  console.log(this.state.inputValue);  // OLD VALUE
  this.setState({
    inputValue: new Date(document.getElementById("time").value).valueOf()
  }); 

  this.props.data.refetch({
    //For some reason
    timestamp: this.state.inputvalue 
    // THERE IS STILL OLD VALUE 
    // because setState work asynchronously 
    // IT WILL BE UPDATED LATER
  });

  console.log(this.state.inputValue); // STILL OLD VALUE
};

要使用事件中的值,您可以简单地使用它的值,而不是通过“异步缓冲区”(状态)传递它。

handleSubmit = event => {
  event.preventDefault();

  console.log(this.state.inputValue);  // OLD VALUE
  const timestamp = new Date(document.getElementById("time").value).valueOf()
  console.log(timestamp);  // NEW VALUE

  // use new value directly
  this.props.data.refetch({
    timestamp: +timestamp
    // convert to int
  });

  // save in state - IF NEEDED at all
  this.setState({
    inputValue: timestamp
  });
};

当然,使用 setState 回调也是一个很好的解决方法。

请记住,您可以进行 2 次渲染 - 一次在状态更改时,第二次在数据到达时。如果不是真的需要在状态中存储值,您可以避免一次不必要的渲染。


推荐阅读