简体   繁体   English

如何在没有导航的情况下从一个组件获取价值到另一个页面/组件?

[英]How to get value from one component to another page/component without navigation?

I have a navbar component in which there is an input search bar.我有一个navbar组件,其中有一个输入搜索栏。 Currently I am taking the value of the search bar and navigate to the Results component and access the input value useParams .目前我正在获取搜索栏的值并导航到Results组件并访问输入值useParams

I have the let [ result, setResult ] = useState([]);我有let [ result, setResult ] = useState([]); in my Results component because the results can change after the search is entered with buttons on the page.在我的Results组件中,因为在使用页面上的按钮输入搜索后结果可能会发生变化。 The problem is that I cannot set the initial result while defining the useState because I am fetching from an API.问题是我无法在定义useState时设置初始结果,因为我正在从 API 中获取数据。

So every time I render, I first get an empty array and failed promise, after which I get the desired one.所以每次渲染时,我首先得到一个空数组并失败 promise,之后我得到了想要的。 How to fix this?如何解决这个问题? I need the search bar to be in the navbar.我需要搜索栏位于导航栏中。

This is the code.这是代码。 New to React. React 新手。

const Navbar = () => {

    let navigate = useNavigate();
    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            let value = event.target.value;
            navigate(`/results/${value}`); 
        }
    }
    
    return (
        <nav className='navigation'>
            <div className='left-slot'>
                <button>runtime</button>
            </div>

            <div className="middle-slot">
                <input className="after" 
                placeholder="get runtimes" onKeyDown={handleKeyDown}>
                </input>
            </div>

            <div className='right-slot'>
                <button>How It Works</button>
                <button>Coming Soon</button>
            </div>
        </nav>
    );
}
const Results = () => {

    let { value } = useParams();
    let [ result, setResult ] = useState();

    useEffect(() => {
        fetchArrayByPage(value, page, option).then(res => setResult(res))
    }, [value])

    console.log(value);
    console.log(result);
    
    return (<div></div>)

}

try a wrapping function for fetching and setting.尝试包装 function 来获取和设置。 i would suggest something like this:我会建议这样的事情:

async function handleResults(){
    const res = await fetchArrayByPage(value, page, option)
    setResult(res)
}

then you can call it inside useEffect然后你可以在 useEffect 中调用它

I'm not entirely sure why your code does not work, so I'll provide three options.我不完全确定为什么您的代码不起作用,因此我将提供三个选项。

Option 1 - If your problem is value is undefined.选项 1 - 如果您的问题是value未定义。

Change your useEffect in Results to this:Results中的useEffect更改为:

useEffect(() => {
  fetchArrayByPage(value && value.length ? value : '', page, option).then(res => setResult(res))
}, [value]);

Option 2 - If you need to pass props and Navbar and Results are not on separate routes.选项 2 - 如果您需要传递道具, NavbarResults不在单独的路线上。

Just pass value as props from Navbar to Results .只需将value作为道具Navbar传递到Results

Option 3 - Passing components without props.选项 3 - 在没有道具的情况下传递组件。

Use the Context API .使用上下文 API This enables you to share data across components without needing to manually pass props down from parent to child.这使您能够跨组件共享数据,而无需手动将 props 从父级传递给子级。

  1. Initialize variables in context.在上下文中初始化变量。
  • Create separate file containing context.创建包含上下文的单独文件。
import React, { createContext } from 'react';

const NavbarContext = createContext(null);

export default NavbarContext;
  • Import said context to App.js or App.tsx if you're using Typescript.如果您使用的是 Typescript,请将所述上下文导入App.jsApp.tsx
  • Declare variables and store them in an object for later reference.声明变量并将它们存储在一个 object 中以备后用。
const [value, setValue] = useState('');
...

const variables = {
    value,
    setValue,
    ...,
};
  • Wrap with Provider.用提供者包装。 Pass context variables to the Provider, enabling components to consume variables .将上下文变量传递给提供者,使组件能够使用variables
return (
  <NavbarContext.Provider value={variables}>
    ...
  </NavbarContext.Provider>
);
  1. Import and use all your variables in Navbar and Results .NavbarResults中导入并使用所有变量。
const { value, setValue, ... } = useContext(NavbarContext);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM