React中如何传递Props?父组件向子组件传Props报错及状态更新函数传递问题求助
Hey there! Let's break down your two React issues one by one.
1. Fixing the "cannot read properties of undefined (reading 'map')" error
The error pops up because your Listing component tries to run map on det when it's undefined at some point. Even though you initialize userDet with an array in the parent, edge cases (like if the parent ever sets userDet to undefined, or temporary prop gaps during rendering) can trigger this.
Here are two reliable fixes:
Option 1: Set a default prop value for det
Give det an empty array as a fallback so it's never undefined:
function Listing({ det = [] }) { // Default to empty array return( <> {det.map((items, index) => { const { name, age } = items; return ( <div key={index}> {/* Don't forget the key prop! React requires this for list items to avoid warnings */} <h1>{name}</h1> <h2>{age}</h2> </div> ); })} </> ); }
Option 2: Use optional chaining (?.)
This safely skips the map call if det is undefined or null:
function Listing({ det }) { return( <> {det?.map((items, index) => { // Optional chain here prevents the error const { name, age } = items; return ( <div key={index}> <h1>{name}</h1> <h2>{age}</h2> </div> ); })} </> ); }
2. Passing setUserDetails to the Ban component
Absolutely! This is a core React pattern for managing shared state across components. Since userDet lives in ApplicationSec, you can pass the setUserDetails function (or a helper function that uses it) to Ban as a prop, letting Ban trigger updates to the parent's state.
Here's how to implement it:
Step 1: Update the parent component to pass the state updater
function ApplicationSec() { const details = [ { name: "sam", age: 15 }, { name: "Kyi", age: 23 }, ]; const [userDet, setUserDetails] = useState(details); // Optional: Create a helper function for cleaner state updates const addNewUser = (newUser) => { // Use the functional update form to ensure you're working with the latest state setUserDetails(prevUsers => [...prevUsers, newUser]); }; return ( <> {/* Pass the helper function (or setUserDetails directly) to Ban */} <Ban addNewUser={addNewUser} /> <Listing det={userDet} /> </> ); }
Step 2: Use the prop in the Ban component
function Ban({ addNewUser }) { const handleAddUser = () => { // Call the function from the parent with a new user object addNewUser({ name: "Alice", age: 28 }); }; return ( <button onClick={handleAddUser}>Add New User</button> ); }
The functional update form (prevUsers => [...prevUsers, newUser]) is a best practice here—it ensures you're always using the most up-to-date state, preventing bugs if multiple updates happen quickly.
内容的提问来源于stack exchange,提问作者SingUser

