Solve the problem of getting undefined in React routing attributes
P粉696891871
P粉696891871 2023-08-14 14:56:23
0
2
543
<p>I want to send some properties (<code>loading</code> and <code>getContacts</code>) to a component in ReactJS. I'm using routing to get each path, but the result is undefined in the target component. How is this going? </p> <pre class="brush:php;toolbar:false;">const App = () => { const [getContacts, setContacts] = useState([]); const [loading, setLoading] = useState(false); return( <div className='App'> <Navbar/> <Routes> <Route path='/' element = {<Navigate to ="/contacts"/>}/> <Route path='/contacts' loading= {loading} contacts= {getContacts} element= {<Contacts/>} /> <Route path="/contacts/add" element = {<AddContact/>}/> <Route path = "/contacts/:contactId" element = {<ViewContact/>}/> <Route path = "/contacts/edit/:contactId" element = {<EditContact/>}/> <Route path="*" element={ <div className='text-light py-5'> Not Found! </div>} /> </Routes> </div> ); export default App;</pre> <p>In Contact.jsx I have: </p> <pre class="brush:php;toolbar:false;">const Contacts = ({ contacts, loading }) => { return ( <> <div>{contacts}</div> <div>{loading}</div> </> ); }; export default Contacts;</pre> <p>But they are all undefined. </p>
P粉696891871
P粉696891871

reply all(2)
P粉806834059

You are passing props to your <Route/> component.

<Route
  path="/contacts"
  loading={loading}
  contacts={getContacts}
  element={<Contacts />}
/>

But you should pass them to your actual <Contacts/>Component

<Route
  path="/contacts"
  element={<Contacts loading={loading} contacts={getContacts} />}
/>
P粉852578075

Try putting the state variable directly into the child element:

<Route path='/contacts' element={<Contacts loading={loading} contacts={getContacts}/>} />
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!