简体   繁体   中英

Why are my props null when I use a method call inside render with JSX?

I have a FileList component that has child File components. This was working fine:

<tbody id="documents">
    {files.map((file, i) => {
      return (
        <File
          key={i}
          id={file.id}
          name={file.name}
          path={file.path_lower}
          tags={file.tags || []}
          />
        );
      })}
</tbody>

Then, I re-worked it a little when I was playing around and for some reason this isn't working (I'm getting a js error that indicates that the props are not being set on File). Essentially the code inside tbody got extracted into a helper method. My hunch is it has something to do with 'this', but in both cases, I'm operating on the same 'files' variable so that's not making sense to me.

I'm curious why - anyone know?

Here's the updated code:

render() {

    const files = this.state.files;
    const elementsHtml = files.map((file, index) => {
        return (
        <File>
          key={index}
          id={file.id}
          name={file.name}
          path={file.path_lower}
        </File>
        );
});

return (
  <table>
    <thead>          
        <th key="name">
          Title
        </th>
        <th alignleft="false" key="tag">
          Categories
        </th>
    </thead>
    <tbody id="documents">
      { elementsHtml }
    </tbody>
  </table>
)}}

In your last example, you are rendering File component wrong. You are not passing props to it, you are rendering it with some children. See:

<File>
...
name={file.name}
...
</File>

not

<File ... name={file.name}... />

So, change it like that:

    <File
      key={index}
      id={file.id}
      name={file.name}
      path={file.path_lower}
    />

Also, avoid using indexes as keys. You have a file id there, use it as key.

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