I'm trying to render out a list of titles by calling map on state from inside the <MyContext.Consumer>
component but the code is not returning the list items. However, if I do a console.log(dataImTryingToMap);
it shows exactly what I'm trying to render. The <ul>
is rendered but no <li>
's are. There are no errors thrown by create-react-app. What am I missing??? Here is the consumer component:
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => {
<li>{context.state.subjects[subject].title}</li>;
console.log(context.state.subjects[subject].title);
})}
</ul>
)}
</MyContext.Consumer>
The console log returns exactly the data I'm looking for, but nothing shows on the screen.
And here is the state from the <MyContext.MyProvider>
component:
state = {
subjects: {
subject0: {
title: "Math",
description: "",
cards: {
card1: {
note: "",
answer: ""
}
}
},
subject1: {
title: "history",
description: "",
cards: {
card1: {
note: "",
answer: ""
}
}
}
}
};
Thanks for any help!
You are not returning anything from the Array.map()
callback:
{Object.keys(context.state.subjects).map(subject => {
<li>{context.state.subjects[subject].title}</li>; <-- this is not returned
console.log(context.state.subjects[subject].title);
})}
const contextValue = { state: {"subjects":{"subject0":{"title":"Math","description":"","cards":{"card1":{"note":"","answer":""}}},"subject1":{"title":"history","description":"","cards":{"card1":{"note":"","answer":""}}}}}}; const MyContext = React.createContext(); const Example = () => ( <MyContext.Consumer> {context => ( <ul> {Object.keys(context.state.subjects).map(subject => { console.log(context.state.subjects[subject].title); return ( <li key={subject}>{context.state.subjects[subject].title}</li> ); })} </ul> )} </MyContext.Consumer> ); const Demo = ({ value }) => ( <MyContext.Provider value={value}> <Example /> </MyContext.Provider> ); ReactDOM.render( <Demo value={contextValue} />, demo );
<script crossorigin src="https://unpkg.com/react@16.3/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16.3/umd/react-dom.development.js"></script> <div id="demo"> </demo>
You haven't returned anything from inside the map function and hence it doesn't render anything. Either return it explicitly like
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => {
return <li>{context.state.subjects[subject].title}</li>;
})}
</ul>
)}
</MyContext.Consumer>
or implicitly like
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => (
<li>{context.state.subjects[subject].title}</li>;
))}
</ul>
)}
</MyContext.Consumer>
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.