[英]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 我一直在学习react和redux来开发一个Web应用程序(使用来自Dan和Joe的egghead.io课程),即使多次看课程,我也似乎无法工作
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. 我基本上试图使用.map()函数渲染一个项目数组,并且没有渲染任何东西,我在之后映射数组以检查是否正在以正确的状态触发重新渲染。 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. 控制台日志打印数组中的所有项目(首先没有,然后是0,然后是[0,1]等)但是组件没有被渲染。 I've put a console log inside the component's render method and it never gets called
我在组件的render方法中放置了一个控制台日志,它永远不会被调用
How can the console.log be working in the .map() but not be rendering the component? console.log如何在.map()中工作但不能渲染组件?
EDIT: Full TaskManager component: https://gist.github.com/Kylar13/6e9b58852f22b64fe5281ed905bf2bc4 编辑:完整的TaskManager组件: https ://gist.github.com/Kylar13/6e9b58852f22b64fe5281ed905bf2bc4
EDIT 2: Task component: 编辑2:任务组件:
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: 也许你只需要将Task作为一个函数调用,例如:
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. 它当然不是一个优雅的解决方案,但由于某种原因,我不能让.map()函数生成的组件重新呈现而不直接引用状态。 If anyone has insight on why this is I'd love to hear it!
如果有人知道为什么这是我喜欢听到它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.