Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript GraphQL突变后设置状态不工作_Javascript_Reactjs_Typescript_Graphql_React Hooks - Fatal编程技术网

Javascript GraphQL突变后设置状态不工作

Javascript GraphQL突变后设置状态不工作,javascript,reactjs,typescript,graphql,react-hooks,Javascript,Reactjs,Typescript,Graphql,React Hooks,如果变异成功,我将尝试在“`submitForm()”的.then中setAdded到true。如果这是真的,我想显示SuccessfulMessage()中的消息。然而,当我记录添加的值时,我一直看到false 由于添加了,未更改为true。当变异成功时,我看不到任何消息。为什么它没有改变 export default function AddUserPage() { const [state, setState] = useState({ firstName: '', l

如果变异成功,我将尝试在“`submitForm()”的.then中
setAdded
true
。如果这是真的,我想显示SuccessfulMessage()中的消息。然而,当我记录添加的值时,我一直看到false

由于添加了
未更改为true。当变异成功时,我看不到任何消息。为什么它没有改变

export default function AddUserPage() {
  const [state, setState] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    phoneNumber:'',
    loggedIn: false,
  });  

  const [added, setAdded] = useState(false);

  function SuccessMessage(){
    if (added)
    {
      console.log('User Added');
      return (
      <Typography>
        User Added
        </Typography>)
    }
  }

  useEffect(() => {
    if(added){
      SuccessMessage();
    }
  },[] );

function submitForm(AddUserMutation: any) {
    const { firstName, lastName, email, password, phoneNumber } = state;
    if (firstName && lastName && email && password && phoneNumber) {
      AddUserMutation({
        variables: {
          firstName: firstName,
          lastName: lastName,
          email: email,
          password: password,
          phoneNumber: phoneNumber,
        },
      }).then(({ data }: any) => {
        setAdded(true);
        console.log('doing', added);
        console.log('ID: ', data.createUser.id);
        console.log('doing', added);
      })
        .catch(console.log)
    }
  }

  return (
    <Mutation mutation={AddUserMutation}>
      {(AddUserMutation: any) => (
        <div>
          <PermanentDrawerLeft></PermanentDrawerLeft>
          <Formik
            initialValues={{ firstName: '', lastName: '', email: '', password: '', phoneNumber: '' }}
            onSubmit={(values, actions) => {
              setTimeout(() => {
                alert(JSON.stringify(values, null, 2));
                actions.setSubmitting(false);
              }, 1000);
            }}
            validationSchema={schema}
          >
            {props => {
              const {
                values: { firstName, lastName, email, password, phoneNumber },
                errors,
                touched,
                handleChange,
                isValid,
                setFieldTouched
              } = props;
              const change = (name: string, e: any) => {
                e.persist();
                handleChange(e);
                setFieldTouched(name, true, false);
                setState( prevState  => ({ ...prevState,   [name]: e.target.value })); 
              };
              return (
                <div className='main-content'>
                  <form style={{ width: '100%' }} 
                  onSubmit={e => {e.preventDefault();
                    submitForm(AddUserMutation);SuccessMessage()}}>
                    <div>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="firstName"
                        name="firstName"
                        helperText={touched.firstName ? errors.firstName : ""}
                        error={touched.firstName && Boolean(errors.firstName)}
                        label="First Name"
                        value={firstName}
                        onChange={change.bind(null, "firstName")}
                      />
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="email"
                        name="email"
                        helperText={touched.email ? errors.email : ""}
                        error={touched.email && Boolean(errors.email)}
                        label="Email"
                        value={email}
                        onChange={change.bind(null, "email")}
                      />
                      <Button
                      type="submit"
                      disabled={!isValid || !email || !password}
                      >
                        Add User</Button>
                    </div>
                  </form>
                </div>
              )
            }}
          </Formik>
        </div>
      )
      }
    </Mutation>
  );
}
导出默认函数AddUserPage(){
常量[状态,设置状态]=使用状态({
名字:'',
姓氏:“”,
电子邮件:“”,
密码:“”,
电话号码:“”,
洛格丁:错,
});  
const[added,setAdded]=useState(false);
函数SuccessMessage(){
如有(新增)
{
console.log('User Added');
返回(
用户添加
)
}
}
useffect(()=>{
如有(新增){
成功消息();
}
},[] );
函数submitForm(addUserVaritation:any){
const{firstName,lastName,email,password,phoneNumber}=state;
if(firstName&&lastName&&email&&password&&phoneNumber){
添加用户突变({
变量:{
名字:名字,
lastName:lastName,
电邮:电邮,,
密码:密码,
电话号码:电话号码,
},
})。然后({data}:any)=>{
setAdded(真);
console.log('do',添加);
log('ID:',data.createUser.ID);
console.log('do',添加);
})
.catch(console.log)
}
}
返回(
{(AddUserMutation:any)=>(
{
设置超时(()=>{
警报(JSON.stringify(值,null,2));
动作。设置提交(错误);
}, 1000);
}}
validationSchema={schema}
>
{props=>{
常数{
值:{firstName,lastName,email,password,phoneNumber},
错误,
感动的,
handleChange,
是有效的,
Setfieldtouch
}=道具;
常量更改=(名称:字符串,e:any)=>{
e、 坚持();
handleChange(e);
setFieldTouched(名称、真、假);
setState(prevState=>({…prevState,[名称]:e.target.value}));
};
返回(
{e.preventDefault();
submitForm(AddUserMutation);SuccessMessage()}>
添加用户
)
}}
)
}
);
}
您的
控制台.log()
在调用
setAdded
后,不会直接显示
true
,因为状态更新是异步的,只有在下次渲染时才可见。此外,您的
SuccessMessage
也不会被触发,因为您没有为
useffect()
提供任何依赖项。这意味着它只能在挂载后调用

您需要将
added
添加到依赖项列表中:

useEffect(() => {
    if(added){
        SuccessMessage();
    }
},[added]);
但实际上我看不出有任何理由在
useffect
中触发它。为什么不直接在变异处理程序中调用它呢

如果已经在使用钩子,也可以使用

此外,您不能从处理程序返回JSX。它不会做任何事情。即使知道在哪里显示您的
用户添加的
,您应该如何反应?您必须根据状态呈现组件本身中的所有内容。

抱歉,但是。。。 。。。这看起来像是一个滥用反应的好例子。。。跳过基本教程、文档和混合随机过时示例的结果

  • useState
    (和
    setState
    )的异步性质-您不能期望更新值
  • 使用
    useffect
    param而不知道它如何影响行为
  • “使用效果”完全不需要
  • 从事件处理程序返回组件,而不是[数据驱动]条件呈现
  • 如果使用了
    usemotation
    ,则不需要将突变作为参数传递给事件处理程序
  • 如果您使用的是Formik(带有字段验证),那么在处理程序中检查参数(字段)是完全不必要的
  • 如果变量props名称匹配,您可以简单地使用
    变量:{…state}
  • Formik管理值,您不需要使用本地状态复制该值-任何原因
  • 福米克也有钩子;)使用
    useFormik()
  • 。。。事件处理程序,绑定

如果您已经在使用钩子,为什么不也使用钩子呢?如果您在setAdded(true)行之后添加一个console.log(),它会显示吗?根据我的代码,实际上无法理解如何使用它。你能帮忙吗@trixnNope,它不显示。它一直在说假话。这就是问题所在@rrdI这么做了。它现在将“用户添加”消息打印到控制台。来自SuccessMessage()函数,但仍不返回错误消息,即typography@a125这不是react的工作原理。不能在处理程序中返回JSX。你应该如何反应,甚至知道在哪里渲染?要呈现的所有内容都必须由组件返回。通过更改将触发重新渲染的状态来更改渲染内容。在表单末尾添加
{added&&successessage()}
。谢谢你的帮助:)谢谢你的建议。我正试图一步一步地修改我的代码。你能看看这个吗?