如何解决useEffect缺少依赖项“ Dispatch”

时间:2020-02-06 00:21:35

标签: reactjs

你好,我的陪同人员有问题,我不确定如何对我的派遣单做出回应:

 const { messages } = ChatReducer;
  const [isTyping, setIsTyping] = useState(false);
  console.log(isTyping)
  useEffect(() => {
    if (messages[messages.length - 1].type === 'bot') {
      setIsTyping(true);
      const timeoutId = setTimeout(() => {
        setIsTyping(false);
        dispatch(wait_end());
      }, 3000);
    }
  }, [messages]);

  useEffect(() => 
  dispatch(answer_Message(['hi ?','hi two'])
  ), []);
return (
  <>
{messages.map((message, index) => (
          <>
            {message.text ? (
              <Styled.MessageFlexColumn ref={messagesEndRef} key={index}>
                {message.type === 'user' ? (
                  <UserText key={index}>{message.text}</UserText>
                ) : (
                  <BotText
                    key={index}
                    isTyping={isTyping && index === messages.length - 1}
                  >
                    {message.text}
                  </BotText>
                )}
                <Styled.Status />
              </Styled.MessageFlexColumn>
            ) : (
              ''
            )}
            <div ref={messagesEndRef} />
          </>
        ))}
  </>
)

操作:

export const checkMessage = text => {
  return dispatch => {
    dispatch(sendMessage(text));
    dispatch(wait_anwser());
    dispatch(botMessage(verify(text)));
  };
};

export const answer_Message = text => {
  return dispatch => {
    text.map((message, index) => {
      dispatch(botMessage(message));
    })
  }
}

我的useEffect和状态也有问题 我基本上是用它来发送一系列初始消息以显示在我的聊天中:

  useEffect(() => 
  dispatch(answer_Message(['hi ?','hi two'])
  ), []);

问题是,发送2个文本时 我的isTyping状态只有一次 甚至是2个文本,如果不输入,请输入我的姓名:

if(messages [messages.length-1] .type ==='bot'

警报陪同:

Line 70:6:   React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array
  Line 74:6:   React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array

1 个答案:

答案 0 :(得分:0)

我不认为您也需要在函数分派时分派它,也可以尝试将分派作为依赖项添加到[dispatch]