我试图通过从<MyContext.Consumer>
组件内部调用state上的map来呈现标题列表,但是代码未返回列表项。但是,如果我执行console.log(dataImTryingToMap);
,则会准确显示我要呈现的内容。 <ul>
被渲染,但是没有<li>
。 create-react-app没有引发任何错误。我在想什么???这是消费者组件:
<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: ""
}
}
}
}
};
感谢您的帮助!
答案 0 :(得分:0)
您没有从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>
答案 1 :(得分:0)
您还没有从map函数内部返回任何内容,因此它不会呈现任何内容。要么像
那样显式地返回它var funcs = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function(param) { // and store them in funcs
console.log("My value: " + param); // each should log its value.
};
}
for (var j = 0; j < 3; j++) {
funcs[j](j); // and now let's run each one to see with j
}
或隐含喜欢
<MyContext.Consumer>
{context => (
<ul>
{Object.keys(context.state.subjects).map(subject => {
return <li>{context.state.subjects[subject].title}</li>;
})}
</ul>
)}
</MyContext.Consumer>