Issue in NextJS / ReactJS while clicking on a button to load a different component into the current component

huangapple go评论77阅读模式
英文:

Issue in NextJS / ReactJS while clicking on a button to load a different component into the current component

问题

在NextJS中,我有3个组件"Sidebar","Woven"和"ToolsPage",下面附上了各自的代码。

ToolsPage:

import Woven from './components/weaved';
import Sidebar from './sidebar';
import { useState } from 'react';

const ToolsPage = () => {
  const [selectedTool, setSelectedTool] = useState('');

  const handleToolClick = (tool: string) => {
    setSelectedTool(tool);
  };

  const renderToolComponent = () => {
    if (selectedTool === 'weaviate') {
      console.log("inside render");
      return <Woven />;
    }
    return <></>;
  };

  return (
    <>
      <Sidebar onToolClick={handleToolClick} />
      <div>
        {selectedTool ? (
          // Render the selected tool component
          <>
            <div>{selectedTool}</div>
            {renderToolComponent()}
          </>
        ) : (
          <></>
        )}
      </div>
    </>
  );
};

export default ToolsPage;

Woven工具组件:

import { useState } from "react";

const Woven = async () => {
  const [weaveApiKey, setWeaveApiKey] = useState('');
  const [weaveURL, setWeaveURL] = useState('');

  return (
    <>
      <form>
        <label>
          Weaviate API key:
          <input
            type="text"
            value={weaveApiKey}
            onChange={(e) => setWeaveApiKey(e.target.value)}
          />
        </label>
        <br />
        <label>
          Weaviate Cluster URL:
          <input
            type="text"
            value={weaveURL}
            onChange={(e) => setWeaveURL(e.target.value)}
          />
        </label>
        <br />
      </form>
    </>
  );
};

export default Woven;

Sidebar组件:

type SidebarProps = {
  onToolClick: (tool: string) => void;
};

const Sidebar: React.FC<SidebarProps> = ({ onToolClick }) => {
  const toolNames = ['weaviate']; // 添加其他工具名称

  return (
    <div>
      <h2>Tools</h2>
      {toolNames.map((tool, index) => (
        <button key={index} onClick={() => onToolClick(tool)}>
          {tool}
        </button>
      ))}
    </div>
  );
};

export default Sidebar;

这是你提供的代码的翻译部分。如果需要进一步的帮助或有其他问题,请随时提出。

英文:

In NextJS, I have 3 components "Sidebar", "Woven" and "ToolsPage", the respective codes are attached below.

ToolsPage:

&quot;use client&quot;
import Woven from &#39;./components/weaved&#39;;
import Sidebar from &#39;./sidebar&#39;;
import { useState } from &#39;react&#39;;

const ToolsPage = () =&gt; {
  const [selectedTool, setSelectedTool] = useState(&#39;&#39;);

  const handleToolClick = (tool: string) =&gt; {
    setSelectedTool(tool);
  };

  const renderToolComponent = () =&gt; {
    if (selectedTool === &#39;weaviate&#39;) {
      console.log(&quot;inside render&quot;)
      return &lt;Woven /&gt;;
    }
    return &lt;&gt;&lt;/&gt;;
  };

  return (
    &lt;&gt;
      &lt;Sidebar onToolClick={handleToolClick} /&gt;
      &lt;div&gt;
        {selectedTool ? (
          // Render the selected tool component
          &lt;&gt;
            &lt;div&gt;{selectedTool}&lt;/div&gt;
            {renderToolComponent()}
          &lt;/&gt;
        ) : (
          &lt;&gt;&lt;/&gt;
        )}
      &lt;/div&gt;
    &lt;/&gt;
  );
};

export default ToolsPage;

Woven tool component:

&quot;use client&quot;

import { useState } from &quot;react&quot;

const Woven = async () =&gt; {
const [weaveApiKey,setWeaveApiKey] = useState(&#39;&#39;)
const [weaveURL,setWeaveURL] = useState(&#39;&#39;)

return(
    &lt;&gt;
    &lt;form&gt;
    &lt;label&gt;
          Weaviate API key:
          &lt;input
            type=&quot;text&quot;
            value={weaveApiKey}
            onChange={(e) =&gt; setWeaveApiKey(e.target.value)}
          /&gt;
        &lt;/label&gt;
        &lt;br/&gt;
        &lt;label&gt;
          Weaviate Cluster URL:
          &lt;input
            type=&quot;text&quot;
            value={weaveURL}
            onChange={(e) =&gt; setWeaveURL(e.target.value)}
          /&gt;
        &lt;/label&gt;
        &lt;br/&gt;
        &lt;/form&gt;
        &lt;/&gt;
)}

export default Woven

Sidebar component:

&quot;use client&quot;

type SidebarProps = {
  onToolClick: (tool: string) =&gt; void;
};

const Sidebar: React.FC&lt;SidebarProps&gt; = ({ onToolClick }) =&gt; {
  const toolNames = [&#39;weaviate&#39;]; // Add other tool names as needed

  return (
    &lt;div&gt;
      &lt;h2&gt;Tools&lt;/h2&gt;
        {toolNames.map((tool,index) =&gt; (
          &lt;button key= {index} onClick={() =&gt; onToolClick(tool)}&gt;
            {tool}
          &lt;/button&gt;
        ))}
    &lt;/div&gt;
  );
};

export default Sidebar;

Here I hardcoded only one tool called "weaviate"
This is the sample output screen if I click on the weaviate button (The component did not appear):Issue in NextJS / ReactJS while clicking on a button to load a different component into the current component

My main motive here is to load the Woven component in the ToolsPage on clicking the weaviate button as shown in the picture.

Here the code enters the renderComponent() function successfully (as shown using console log statement in ToolsPage component but it is repeating multiple times continuously and screen got struck)

But the Woven component is not appearing after clicking on the hardcoded weaviate button.


I tried another case- I initiated the state directly to "weaviate" in the ToolsPage line 7

const [selectedTool, setSelectedTool] = useState(&#39;weaviate&#39;);

Then the component appeared:

Issue in NextJS / ReactJS while clicking on a button to load a different component into the current component

But on clicking the button gives the same issue.

Final target: On clicking the button should load the Woven component without the multiple re-renderings

答案1

得分: 2

尝试创建一个独立的组件用于 renderToolComponent 并将 selectedTool 作为其 props 传递。还要从 Woven 组件中删除 async,然后再试一次。如果您想在该组件中发出 API 调用以从服务器端获取数据并进行渲染,那么请按照此处说明在组件声明之前定义一个异步函数:https://nextjs.org/docs/app/building-your-application/data-fetching/fetching

英文:

Try creating a separate component for the renderToolComponent and pass selectedTool as its props. Also, remove async from the Woven component and try again and if you want to make an API call in that component to fetch data on server side and render it then define an async function above the component declaration as explained here: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching

huangapple
  • 本文由 发表于 2023年6月18日 19:19:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定