从 React Context API 渲染函数中的地图函数渲染 HTML

Rendering HTML from map function in React Context API render function

我试图通过从 <MyContext.Consumer> 组件内部调用 map on state 来呈现标题列表,但代码没有返回列表项。但是,如果我执行 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>

控制台日志 returns 正是我要查找的数据,但屏幕上没有任何显示。

这是 <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>

您还没有 return 从地图函数内部编辑任何东西,因此它不会呈现任何东西。要么return它明确喜欢

<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>