因此,下面的代码正在更新inputValue的状态,但是由于某些原因,由于显示以下错误,因此未将值传递给查询:
[GraphQL错误]:消息:所需类型为“ Float!”的变量“ $ timestamp”未提供。,位置:[object Object],路径:undefined
所以我的问题是如何将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);
答案 0 :(得分:0)
我知道它已经在其他地方解决了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个渲染-一个在状态更改时渲染,另一个在数据到达时渲染。如果确实不需要以状态存储值,则可以避免一次不必要的渲染。