Ben*_*ins 2 reactjs redux react-redux
我正在尝试使用针对UI使用react 的redux基本用法教程.
当我点击标有"添加待办事项"的按钮时,我在控制台日志中收到此警告(红色但可能是错误?):
warning.js:36警告:支柱类型失败:道具
todos[0].id标记为必需TodoList,但其值为undefined.在TodoList(由Connect(TodoList)创建)中的Connect(TodoList)(在App.js:9)中的div(在App.js:7)在App中(在index.js:12)在Provider中(在index.js) :11)
所以添加的待办事项没有id字段 - 我需要弄清楚如何添加id.
在 actions.js
/*
* action creators
*/
export function addTodo(text) {
return { type: ADD_TODO, text }
}
Run Code Online (Sandbox Code Playgroud)
动作/ index.js
let nextTodoId = 0
export const addTodo = (text) => {
return {
type: 'ADD_TODO',
id: nextTodoId++,
text
}
}
export const setVisibilityFilter = (filter) => {
return {
type: 'SET_VISIBILITY_FILTER',
filter
}
}
export const toggleTodo = (id) => {
return {
type: 'TOGGLE_TODO',
id
}
}
Run Code Online (Sandbox Code Playgroud)
集装箱/ AddTodo.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
export default AddTodo
Run Code Online (Sandbox Code Playgroud)
它看起来像actions/index.js添加待办事项id?
它很难调试,因为由于某些原因,chrome dev工具源缺少我的应用程序的actions和reducers文件夹:
如何让todos [0]拥有唯一的ID?
请注意,当我在id: 1这里添加它确实添加了ID但它不是唯一的:
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false,
id: 1
}
]
case TOGGLE_TODO:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: !todo.completed
})
}
return todo
})
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
也许:
/*
* action creators
*/
export function addTodo(text) {
return { type: ADD_TODO, text }
}
Run Code Online (Sandbox Code Playgroud)
需要id补充?
小智 6
我简要地查看了你的代码,我相信你没有得到它,id因为你没有导入你认为自己的动作创建函数.
在containers/AddTodo.js中:
import { addTodo } from '../actions'
Run Code Online (Sandbox Code Playgroud)
在你的项目中,你有
./src/actions.js
./src/actions/index.js
Run Code Online (Sandbox Code Playgroud)
当您导入或需要任何内容时(不使用上述文件扩展名'../actions'),JS解释器将查看src文件夹中是否存在名为actions.js的文件.如果没有,则会看到是否有一个带有index.js文件的actions文件夹.
既然你有两个,你的AddTodo组件是使用./src/actions.js中的动作创建者导入的,它没有id你原先猜到的属性.
删除该文件,它应该按预期工作.
| 归档时间: |
|
| 查看次数: |
4038 次 |
| 最近记录: |