Reactjs / Graphql:TypeError:Object(...)不是一个函数

时间:2018-08-02 23:30:18

标签: javascript reactjs graphql

选择日期和时间后,单击提交按钮,出现以下错误:

  

TypeError:Object(...)不是函数

该对象所指的是Action,它是一个查询,所以我不明白为什么它说它不是函数。另外,请查看handleSubmit事件,并确保我正确地调用了Action。谢谢!

渲染组件

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()
    });
    Action({
      variables: {
        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(Action, {
  options: props => ({
    variables: {
      timestamp: props.inputValue
    }
  })
})(Calendar);

动作查询

const Action = gql`
  query($timestamp: Float!) {
    action(timestamp: $timestamp) {
      action
      timestamp
      object {
        filename
      }
    }
  }
`;

1 个答案:

答案 0 :(得分:1)

这不是重新查询的正确方法。

代替

Action({
  variables: {
    timestamp: this.state.inputValue
  }
});

尝试

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

    console.log(this.state.inputValue);
    this.setState({
      inputValue: new Date(document.getElementById("time").value).valueOf()
    }, () => {
      this.props.data.refetch({
        timestamp: +this.state.inputValue
      });
      console.log(this.state.inputValue);
    });
  };

如果您不想调用此道具data,则可以在HOC graphql上对其重命名,如下所示:

export default graphql(Action, {
  name: 'WHATEVERNAME'
  options: props => ({
    variables: {
      timestamp: props.inputValue
    }
  })
})(Calendar);

那么您将呼叫this.props.WHATEVERNAME而不是this.props.data

希望它可以帮助:D

顺便说一句,您将handleSubmit方法绑定了3次。您只需要执行一次:

    不建议在渲染中使用
  1. 绑定,因为您将在每次重新渲染时处理绑定:

因此您可能希望将<form onSubmit={this.handleSubmit.bind(this)}>更改为<form onSubmit={this.handleSubmit}>

  1. 您可以像以前一样将其绑定到构造函数上。那没问题。但这有点冗长。我会删除它。

3。handleSubmit = event => {,就像您将方法声明为箭头函数一样,该方法会自动绑定到this。所以我会保留并删除其他2 :)

PS:请注意,在第3项上,如果您要编写handleSubmit(e) {},它将不会绑定到this,因此您需要其他两种方法之一。但同样,数字3是绑定的最有效方法:)只需删除其他2,就可以了。