javascript - 停止中继:查询渲染器为某些 setStates 重新加载数据
问题描述
我目前正在关注这个,我确实让它工作了。但我想知道是否有办法在调用 this.setState() 时阻止查询渲染重新加载数据。基本上我想要的是当我输入文本框时,我还不想重新加载数据,但由于呈现问题,我需要设置状态。我希望仅在单击按钮时重新加载数据,但数据将基于文本框值。
我尝试将文本框值状态与传递给graphql的实际变量分开,但似乎无论变量更改如何,查询都会重新加载。
这是代码 FYR。
const query = graphql`
query TestComponentQuery($accountId: Int) {
viewer {
userWithAccount(accountId: $accountId) {
name
}
}
}
`;
class TestComponent extends React.Component{
constructor(props){
super(props);
this.state = {
accountId:14,
textboxValue: 14
}
}
onChange (event){
this.setState({textboxValue:event.target.value})
}
render () {
return (
<div>
<input type="text" onChange={this.onChange.bind(this)}/>
<QueryRenderer
environment={environment}
query={query}
variables={{
accountId: this.state.accountId,
}}
render={({ error, props }) => {
if (error) {
return (
<center>Error</center>
);
} else if (props) {
const { userWithAccount } = props.viewer;
console.log(userWithAccount)
return (
<ul>
{
userWithAccount.map(({name}) => (<li>{name}</li>))
}
</ul>
);
}
return (
<div>Loading</div>
);
}}
/>
</div>
);
}
}
解决方案
好的,所以我的最后一个答案没有按预期工作,所以我想我会创建一个全新的示例来演示我在说什么。简单地说,这里的目标是在父组件中有一个子组件,只有在收到新道具时才会重新渲染。请注意,我使用了组件生命周期方法shouldComponentUpdate()
来防止Child
组件重新渲染,除非对 prop 进行更改。希望这对您的问题有所帮助。
class Child extends React.Component {
shouldComponentUpdate(nextProps) {
if (nextProps.id === this.props.id) {
return false
} else {
return true
}
}
componentDidUpdate() {
console.log("Child component updated")
}
render() {
return (
<div>
{`Current child ID prop: ${this.props.id}`}
</div>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
id: 14,
text: 15
}
}
onChange = (event) => {
this.setState({ text: event.target.value })
}
onClick = () => {
this.setState({ id: this.state.text })
}
render() {
return (
<div>
<input type='text' onChange={this.onChange} />
<button onClick={this.onClick}>Change ID</button>
<Child id={this.state.id} />
</div>
)
}
}
function App() {
return (
<div className="App">
<Parent />
</div>
);
}
推荐阅读
- node.js - 在 Apple M1 (Big Sur) 上使用 node-gyp 安装本机 Node.js 插件时出错
- python - 打印捕获的异常类型而不打印错误描述
- python - Spark:在 from_json 之后删除空值或仅从 json 获取值
- javascript - Vue提交输入隐藏
- tensorflow - 在树莓派上安装 tensorflow 1.9* 通过修改代码以使用 tf 2 解决
- c++ - 为什么我不能使用 std::tie 从基于范围的对向量中解压缩值 for 循环
- c# - ActionFilterAttribute 中的 GetService 返回 null
- sql - 将两个 LEFT JOINS 连接在一起
- jdbc - 我们如何重置与 Kafka Connect 源连接器关联的状态?
- ios - 以编程方式在 UIScrollView 中安装 UIStackView