简体   繁体   中英

React render using lodash _.forOwn function?

render() {    
  return (
    <SettingPanel>
      {!loading && _.forOwn(accessLogs, function(groupedLogs, date) {
        console.log(date);
        console.log(groupedLogs);
        console.log("=====");
        return <DayLog date={date} accessLogs={groupedLogs} />;
      })}
    </SettingPanel>
  );
}

This code is generating this clientside error for me:

warning.js:33 Warning: Failed prop type: Invalid prop `children` supplied to `SettingPanel`.
    in SettingPanel (created by AccessLogsPanel)
    in AccessLogsPanel (created by inject-AccessLogsPanel-with-teamStore-accessLogsStore)
    in inject-AccessLogsPanel-with-teamStore-accessLogsStore (created by TeamSecurity)

Any glaring mistake I made? I just want to render a <DayLog /> component for each key in accessLogs .

Lodash's _.forOwn() returns an object, which React can't render. Instead of _.forOwn() use _.map() :

render() {    
  return (
    <SettingPanel>
      {!loading && _.map(accessLogs, function(groupedLogs, date) {
        return <DayLog date={date} accessLogs={groupedLogs} />;
      })}
    </SettingPanel>
  );
}

Since lodash _.forOwn returns an object you might need to create an array instead for the children prop to be valid.

Something like this might work:

render() {
  const logs = Object.keys(accessLogs).reduce((result, date) => {
    const groupedLogs = accessLogs[date];
    result.push(<DayLog date={date} accessLogs={groupedLogs} />);
    return result;
  }, []);
  return (
    <SettingPanel>
      {!loading && logs}
    </SettingPanel>
  );
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM