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