0

我试图通过从<MyContext.Consumer>组件内部调用状态映射来呈现标题列表,但代码没有返回列表项。但是,如果我这样做,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: ""
                }
            }
        }
    }
};

谢谢你的帮助!

4

2 回答 2

1

您没有从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>

于 2018-07-13T08:02:03.567 回答
0

您没有从 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>
于 2018-07-13T08:02:19.603 回答