我试图通过从<MyContext.Consumer>
组件内部调用map-on-state来呈现标题列表,但代码没有返回列表项。然而,如果我做console.log(dataImTryingToMap);
,它会准确地显示我试图渲染的内容。已渲染<ul>
,但未渲染<li>
。create-rect应用程序没有引发错误。我缺少什么???这是消费者组成部分:
<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>
控制台日志返回的正是我要查找的数据,但屏幕上没有显示任何内容。
这是来自<MyContext.MyProvider>
组件的状态:
state = {
subjects: {
subject0: {
title: "Math",
description: "",
cards: {
card1: {
note: "",
answer: ""
}
}
},
subject1: {
title: "history",
description: "",
cards: {
card1: {
note: "",
answer: ""
}
}
}
}
};
谢谢你的帮助!
您没有从Array.map()
回调返回任何内容:
{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>
您没有从map函数内部返回任何内容,因此它不会呈现任何内容。要么像一样显式返回
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => {
return <li>{context.state.subjects[subject].title}</li>;
})}
</ul>
)}
</MyContext.Consumer>
或隐含地类似
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => (
<li>{context.state.subjects[subject].title}</li>;
))}
</ul>
)}
</MyContext.Consumer>