【问题标题】:Rerender React component after API is changedAPI 更改后重新渲染 React 组件
【发布时间】:2021-11-06 01:29:39
【问题描述】:

我无法显示我通过 hendleSubmit 函数发布到 api 的消息。消息被发送并添加到数组中,但它不会立即显示,只有在我重新加载页面时才会显示。有人可以帮我解决这个问题吗?

这是我的代码:

export const ConversationForm = () => {
    const { isLoading, data={} } = useQuery(['conversationForm'], () => conversationMessageService.getConversationMessages());
    }
declaration of the component and getting data from api in 'data' array

    <Grid container className={classes.conversation}>
            <SadStates
              states={[
                {
                  when: isLoading,
                  render: <Loader/>
                }
              ]}>
              {data.items===undefined?
                <img src={emptyChatIcon} alt={''}/>:
                <ScrollToBottom mode='bottom' className={classes.scrollBottom}>
                  {data.items.map((message) => {
                    return (
                      <ConversationMessage
                        message={message}
                        key={message.id}
                        customerName={customerName}
                        userName={userName}/>
                    );
                  })}
                </ScrollToBottom>
              }
            </SadStates>
          </Grid>

调用子组件逐条打印消息

     <Formik
        initialValues={{
          userPhone: userPhone,
          customerPhone: customerPhone,
          conversationMessageSender: conversationMessageSender,
          body: '',
          conversationMessageType: 1}}
        onSubmit={handleSubmit}>
        {({}) => (
          <Form>
            <Grid container>
              <Grid item>
                <ConversationInputField inputName='body'/>
              </Grid>
              <Grid item>
                <button type='submit'>
                  <Grid item>
                    <img src={sendIcon} alt={''}/>
                  </Grid>
                </button>
              </Grid>
            </Grid>
          </Form>
        )}
      </Formik>

我在提交时调用 post 方法的表单

  const handleSubmit = async( values, { setSubmitting }) => {

    try {
      await conversationMessageService.createConversatonMessage(values);
      values.body='';
      setSubmitting(false);
    } catch (error) {
      console.log(error);
    }
  };

处理提交函数

【问题讨论】:

    标签: javascript reactjs rerender


    【解决方案1】:

    我在您的代码中没有看到任何地方重新获取提交的数据。您的前端应该如何知道您已在后端将 X 更改为 Y?

    提交后重新获取它并刷新保存数据的本地状态和/或在从后端获取正确值时对本地状态进行乐观更新。

    React 查询是一个非常棒的工具。变异数据还允许您取消先前的查询(开始自动刷新)并进行乐观更新,您可以在其中预测您的状态将是什么样子,以防您正在处理的数据需要更长的时间来加载/非常复杂性,以避免让用户等待。

    【讨论】:

    • useEffect(() =&gt; { refetch(); }, [refetch]);我添加了这个但仍然没有改变我的观点
    • 我再次查看了您的答案并明白了。非常感谢!!!
    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多