React - useEffect 钩子 - componentDidMount 到 useEffect [英] React - useEffect hook - componentDidMount to useEffect

查看:58
本文介绍了React - useEffect 钩子 - componentDidMount 到 useEffect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将其转换为 useEffect 钩子:

I would like to convert this to an useEffect hook:

代码

componentDidMount () {
   this.messagesRef.on('child_added', snapshot => {
    const message = snapshot.val();
    message.key = snapshot.key;
    this.setState({messages: this.state.messages.concat(message 
  )});
});

更新代码

const MessageList = () => {
  const [messages, setMessage] = useState([]);
  const [usernames, setUsernames] = useState('');
  const [contents, setContents] = useState('');
  const [roomId, setRoomId] = useState('');

  const messagesRef = MessageList.props.firebase.database().ref('messages');

  useEffect(() => {
    messagesRef.on('child added', snapshot => {
    const message = snapshot.val();
    message.key = snapshot.key;

    const [messages, setMessages] = useState({messages: messages.concat(message)});
  });
 })
}

现在它给了我一个 useState 不能在回调中使用.

我该如何解决或正确转换?

How can I address this or convert this properly?

推荐答案

有几件事.首先,要修复代码,您可以将 useEffect 更新为:

There are a couple of things there. First, to fix the code, you could update your useEffect to this:

useEffect(() => {
    messagesRef.on('child added', snapshot => {
    const message = snapshot.val();
    message.key = snapshot.key;

    setMessages(messages.concat(message)); // See Note 1
}, []); // See Note 2

注意 1

setMessages 行是您更新状态的方式.useState 与旧的"setState 有点不同,它会完全取代状态值.React 文档 说:

Note 1

The setMessages line is how you update your state. useState is a little bit different from the "old" setState in a sense that will completely replace the state value. React documentation says:

这是因为当我们更新一个状态变量时,我们替换了它的值.这与类中的 this.setState 不同,它将更新的字段合并到对象中.

This is because when we update a state variable, we replace its value. This is different from this.setState in a class, which merges the updated fields into the object.

注意事项 2

React Hooks 改变了我们构建应用的方式,它并不是旧生命周期的真正翻译".

Note 2

React Hooks changes the way we build apps and it is not a real "translation" from the old lifecycles.

最后一行中的空括号 ([]) 将使您的代码类似于"componentDidMount,但最重要的是,将使您的效果只运行一次.

The empty brackets ([]) in the last line, will make your code "similar" to componentDidMount, but most importantly, will make your effect run only once.

Dan Abramov 说(去掉了部分原文):

Dan Abramov said (removed some of the original text):

虽然你可以使用Effect(fn, []),但它并不完全等同.与 componentDidMount 不同,它将捕获 props 和 state.所以即使在回调里面,你也会看到初始的 props 和 state.(...) 请记住,效果的心理模型与 componentDidMount 和其他生命周期不同,试图找到它们的确切等价物可能会让您感到困惑,而不仅仅是帮助.为了提高工作效率,您需要在效果中思考",他们的心智模型更接近于实现同步而不是响应生命周期事件.

While you can useEffect(fn, []), it’s not an exact equivalent. Unlike componentDidMount, it will capture props and state. So even inside the callbacks, you’ll see the initial props and state. (...) Keep in mind that the mental model for effects is different from componentDidMount and other lifecycles, and trying to find their exact equivalents may confuse you more than help. To get productive, you need to "think in effects", and their mental model is closer to implementing synchronization than to responding to lifecycle events.

关于 useEffect 的完整文章此处.

Full article about useEffect here.

这篇关于React - useEffect 钩子 - componentDidMount 到 useEffect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆