简体   繁体   中英

Component in react doesn't render when in .map() function

I've been learning react and redux to develop a web application (Using egghead.io courses from Dan and Joe) and there's something I can't seem to get working even after watching the courses multiple times

I'm basically trying to render an array of items using .map() function and nothing get's rendered, I map through the array right after to check if the re-rendering is being triggered with the right state and it is. Here's the code in question:

{TaskManagerStore.getState().tasks.map(task =>
    <Task key={task.id} task={task} />
)}
{TaskManagerStore.getState().tasks.map( task =>
    console.log(task)
)}

<AddTaskButton onClick={() => (
    TaskManagerStore.dispatch({
        type: 'ADD_TASK',
        title: 'Test task',
        content: 'Hey there!',
        id: testID++
    })
)}/>

The console log prints all items in the array (first nothing, then 0, then [0, 1], etc) but the component is not being rendered. I've put a console log inside the component's render method and it never gets called

How can the console.log be working in the .map() but not be rendering the component?

EDIT: Full TaskManager component: https://gist.github.com/Kylar13/6e9b58852f22b64fe5281ed905bf2bc4

EDIT 2: Task component:

const Task = ({ task }) => {

    return (
        <div className="Task">
            <h3 className="Task-title">{task.title}</h3>
            <p className="Task-content">{task.content}</p>
            <div className="Task-editButton">Edit<i className="fa fa-pencil" aria-hidden="true"/></div>
        </div>
    )
};

Maybe you just have to call Task as a function, eg:

const Task = ({ task }) => {

    return (
        <div key={task.id} className="Task">
            <h3 className="Task-title">{task.title}</h3>
            <p className="Task-content">{task.content}</p>
            <div className="Task-editButton">Edit<i className="fa fa-pencil" aria-hidden="true"/></div>
        </div>
    )
};

{TaskManagerStore.getState().tasks.map(task => Task({ task })}

In your Task component you're passing two props, key and task. I solved the issue by adding an additional prop that refers directly to the state tree, like this...

const tasks = TaskManagerStore.getState().tasks

{tasks.map(task =>
    <Task 
      key={task.id} 
      task={task} 
      tasks={tasks}/>
)}

It's certainly not an elegant solution, but for some reason I can't get the components generated by the .map() function to re-render without referencing the state directly. If anyone has insight on why this is I'd love to hear it!

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