如何使用graphQL在React / Apollo中设置setState()

Kev*_*ski 5 reactjs graphql graphql-js react-apollo

我正在尝试将setState()设置为来自graphQL的查询结果,但是我很难找到如何执行此操作的方法,因为它将始终处于加载状态,或者仅从props中使用。我先设定状态

constructor (props) {
        super(props);
        this.state = { data: [] };
Run Code Online (Sandbox Code Playgroud)

然后我有这个查询

const AllParams = gql`
    query AllParamsQuery {
        params {
            id,
            param,
            input
        }
    }`
Run Code Online (Sandbox Code Playgroud)

当它回来时,我可以用 this.props.AllParamsQuery.params

我应该如何以及何时 this.setState({ data: this.props.AllParamsQuery.params }) 不返回 {data: undefined}

我还没有找到一种方法让它在undefinedAKA loading: true之后等待setState。我试着componentDidMount()componentWillReceiveProps()包括async function(){...await...}但没有成功,我可能做错了。有人知道如何正确执行此操作或有示例吗?

编辑+答案:您不应设置状态,而应将其留在道具中。检查此链接:“为什么在props.js中将props设置为state是亵渎神灵” http://johnnyji.me/react/2015/06/26/why-setting-props-as-state-in-react-is- blasphemy.html 更新道具还有很多问题,但可以在此应用程序创建教程中找到一些很好的示例:https : //www.howtographql.com/react-apollo/8-subscriptions/

Con*_*nor 5

一个简单的解决方案是将 Apollo 查询组件和 React 有状态组件分开。mapStateToProps来自 Redux,使用和转换本地组件状态的传入 props 并不罕见componentWillReceiveProps。然而,这种模式与 Apollo 的<Query />.

因此,只需创建一个单独的组件来获取数据:

...

export class WidgetsContainer extends Component {
  render (
    <Query query={GET_WIDGETS}>
      {({ loading, error, data }) => {
        if (loading) return <Loader active inline="centered" />;

        const { widgets } = data;
        return (
          <Widgets widgets={widgets} />
        )
      }}
    </Query>
  )
}
Run Code Online (Sandbox Code Playgroud)

现在Widgets组件可以setState正常使用:

...
export class Widgets extends Component {
  ...
  constructor(props) {
    super()

    const { widgets } = props;
    this.state = {
      filteredWidgets: widgets
    };
  }

  filterWidget = e => {
    // some filtering logic
    this.setState({ filteredWidgets });
  }

  render() {
    const { filteredWidgets } = this.state;
    return (
      <div>
        <input type="text" onChange={this.filterWidgets} />
        {filteredWidgets.count}
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*x K 1

将其设置为 state 的原因是什么?请记住,Apollo 客户端使用内部 redux 存储来管理查询。如果您尝试根据查询中的某些内容发生变化来触发重新渲染,则应该使用 refetchQueries()。如果您绝对需要将其存储在本地状态中,我假设您可以比较 componentWillReceiveProps 中的 nextProps 来检测加载时(从 apollo 客户端执行查询时返回的值)已更改,然后更新您的状态。