简体   繁体   中英

How to passing data through multiple component in react?

I have 3 components: Layout App Products

My Layout has this form:

                  <form className='d-flex'>
                    <input
                      name='search'
                      className='form-control mr-2 shadow-none'
                      type='search'
                      placeholder='Search'
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                    />
                    <button className='btn btn-outline-secondary' type='submit'>
                      <SearchIcon />
                    </button>
                  </form>

I passed search and setSearch through props.

In my App has this logic:

  const [search, setSearch] = useState('');
    <Layout search={search} setSearch={setSearch}>  
        <Route exact path='/' search={search} component={Products} />
    </Layout>

I pulled the search result from the Layout and created a state in the App and then trying to pass to the Products component.

In the product when I try to console the search result I see only an undefined result

Your method doesn't work because you are passing the search value into the Route component instead of the component it render. You can use the render property of the Route to pass any props you want to the routing component https://reactrouter.com/web/api/Route/route-render-methods

 const [search, setSearch] = useState('');
 <Layout search={search} setSearch={setSearch}>  
    <Route exact path='/'
       render={props=> <Products {...props} search={search} setSearch={setSearch}/>} />
 </Layout>

However, I suggest using a state management tool like redux if the application is big or create a context provider https://reactjs.org/docs/context.html#when-to-use-context .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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