首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >嵌套组件调用的挂钩调用无效

嵌套组件调用的挂钩调用无效
EN

Stack Overflow用户
提问于 2021-06-18 09:55:59
回答 1查看 33关注 0票数 0

我的App.jsx中有以下代码:

代码语言:javascript
运行
复制
render() {
    return (            
        <BrowserView>
            <CreateSession />                         // works just fine
            <QrCode address={CreateSession(this)} />  // throws 'Error: Invalid hook call.'
        </BrowserView>)
}

CreateSession返回一个字符串,该字符串将输入到QrCode中,以生成二维码。我的CreateSession看起来像这样:

代码语言:javascript
运行
复制
const CreateSession = (props) => {

  const userVideo = useRef();
  const partnerVideo = useRef();
  const peerRef = useRef();
  const socketRef = useRef();
  const otherUser = useRef();
  const userStream = useRef();

  useEffect(() => {
    socketRef.current = io.connect("/");
    socketRef.current.emit("join session", props.match.params.roomID);

  // lots of code omitted, source is: https://github.com/coding-with-chaim/native-webrtc/blob/master/client/src/routes/Room.js
   

  return uuid();
};

export default CreateSession;

调用CreateSession以便将uuid直接返回到QrCode中的正确方法是什么?我知道我可以在App.jsx中设置一个状态属性,将其设置为uuid,然后将其传递给QrCode,但是否可以这样做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-18 15:29:09

您可以将CreateSession组件转换为包装器。

代码语言:javascript
运行
复制
const CreateSession = (props) => {

  const userVideo = useRef();
  const partnerVideo = useRef();
  const peerRef = useRef();
  const socketRef = useRef();
  const otherUser = useRef();
  const userStream = useRef();

  const [uuid, setUuid] = useState(null);

  useEffect(() => {
    socketRef.current = io.connect("/");
    socketRef.current.emit("join session", props.match.params.roomID);

    // lots of code omitted, source is: https://github.com/coding-with-chaim/native-webrtc/blob/master/client/src/routes/Room.js
  
    setUuid(uuid());
  });
  
  if (uuid === null) {
    return null;
  }

  return (<>{props.children(uuid)}</>)
};

export default CreateSession;

下面是用法。

代码语言:javascript
运行
复制
render() {
  return (            
    <BrowserView>
      <CreateSession>
        {(uuid) => (<QrCode address={uuid} />)}
      </CreateSession>
    </BrowserView>
  )
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68028402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档