在我的 Redux 商店中,我存储了一个 accountId。<Login>
这在成功授权后由组件存储。该<Login>
组件仅接收accountId
(在 JWT 内部),而不是完整的 Account 对象及其所有属性。
accountId
也可以通过其他组件的其他操作进行修改。
当由于accountId
某种原因被修改时,我想为完整的 Account 文档触发一个新的 GraphQL 查询,并将其存储在 Redux 中。
为此,我创建了一个组件。我最初将 Redux 调度件放入 中componentWillUpdate()
,但后来它不起作用(它没有收到完整的 GraphQL 查询结果)。如果我把它放在render()
下面,它可以工作:
import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { message } from 'antd';
// This service receives an accountId prop from Redux, and returns the complete account record
// to Redux once the graphQL query completes.
class AccountService extends React.Component {
render() {
if( !this.props.accountId ) {
this.props.onAccount( null ); // Logged out -> Redux
} else {
if( this.props.data && this.props.data.error ) {
console.log( this.props.data.error.message );
message.error( this.props.data.error.message, 20 );
}
if( this.props.data && this.props.data.loading === false ) {
if( this.props.data.accountById ) {
let account = {
firstName: this.props.data.accountById.firstName,
lastName: this.props.data.accountById.lastName,
// ...etc.
};
this.props.onAccount( account ); // -> Redux dispatch
}
}
}
return ( null );
}
}
const accountQuery = gql`
query ($accountId: Int!) {accountById(id:$accountId) {
firstName,
lastName,
// ...etc.
}}`;
export default graphql( accountQuery, {
options: ( { accountId } ) => ({ variables: { accountId: accountId || 0 } }),
} )( AccountService );
上述组件按预期工作。但是当我调用调度时它会引发警告:
Warning: setState(...): Cannot update during an existing state transition
所以显然我没有以正确的方式做事。我该如何构建它以便我得到结果并能够在没有警告的情况下将它们存储回 Redux?