首页 > 解决方案 > 停止中继:查询渲染器为某些 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>

        );
    }
}

标签: javascriptreactjsgraphqlrelayjsrelay

解决方案


好的,所以我的最后一个答案没有按预期工作,所以我想我会创建一个全新的示例来演示我在说什么。简单地说,这里的目标是在父组件中有一个子组件,只有在收到新道具时才会重新渲染。请注意,我使用了组件生命周期方法shouldComponentUpdate()来防止Child组件重新渲染,除非对 prop 进行更改。希望这对您的问题有所帮助。

编辑 pedantic-sea-kis3i

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>
  );
}

推荐阅读