Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.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 获取错误为';无法读取null';的属性scrollIntoView;使用时向下滚动代码_Javascript_Reactjs - Fatal编程技术网

Javascript 获取错误为';无法读取null';的属性scrollIntoView;使用时向下滚动代码

Javascript 获取错误为';无法读取null';的属性scrollIntoView;使用时向下滚动代码,javascript,reactjs,Javascript,Reactjs,以下代码经常出现上述错误 const [consumerMessages, setConsumerMesssages] = useState([]) const messagesEndRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current.scrollIntoView({ behavior: "smooth" }); }; useEffe

以下代码经常出现上述错误

 const [consumerMessages, setConsumerMesssages] = useState([])

 const messagesEndRef = useRef(null);

 const scrollToBottom = () => {
        messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
      };
 
useEffect(() => {
        scrollToBottom()
      }, [consumerMessages]);
以下是codesandbox链接:

发生此错误的原因以及适当的解决方案是什么?

问题 基本上,在初始渲染时,ref没有作为当前ref值附加到DOM节点,因此还没有定义
messagesEndRef.current

解决方案 使用空检查:

messagesEndRef.current &&
  messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
或使用(
?。
):

演示

OK错误消失了,但是,为什么新错误传播不可编辑实例的尝试无效。为了实现可移植性,非数组对象必须具有[Symbol.iterator]()方法。@Pranav是的,我也这么怀疑,并尝试了“发送消息”按钮。我看到您从localStorage加载,但如果从未使用过localStorage,请将
textMessage
状态设置为未定义。另外,当保存到localStorage时,您需要
JSON.stringify
它,然后在读取时
JSON.parse
它。哦,是的,现在我知道了,谢谢……@Pranav我不太确定您所说的“最后一条消息变得如此深入”是什么意思,但是如果您指的是输入“气泡”后面/下面的消息列表,是的,这似乎非常有趣。如果不是,你能澄清什么是“深”吗?让我们来看看。
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });