gpt4 book ai didi

reactjs - "dispatch"未定义

转载 作者:行者123 更新时间:2023-12-02 16:16:15 24 4
gpt4 key购买 nike

我一直在调试这个程序,但没有任何线索,我跟着this教程逐字逐句地尝试制作一个 TODO 应用程序,但我无法弄清楚为什么会收到此错误消息。

./src/containers.js
Line 12: 'dispatch' is not defined no-undef
Line 13: 'dispatch' is not defined no-undef

组件.js

import React from 'react'

class Todo extends React.Component {

render() {
const { todo } = this.props

if (todo.isDone) {
return <strike>{todo.text}</strike>
} else {
return <span>{todo.text}</span>
}
}
}

export default class TodoList extends React.Component {
render() {

const {todos, toggleTodo, addTodo } = this.props
console.log(toggleTodo)

return (
<div className="todo">
<input type="text" placeholder="Add todo"/>
<ul className='todo__list'>
{todos.map(t => (
<li key={t.id} className='todo__item'>
<Todo todo={t} />
</li>
))}
</ul>
</div>
)
}
}

容器.js

import * as components from './components.js'
import { addTodo, toggleTodo } from './actions.js'
import { connect } from 'react-redux'

const mapStateToProps = (state) => {
return {todos: state}
}

const mapDispatchToProps = (state) => {
return {
addTodo: text => dispatch(addTodo(text)),
toggleTodo: id => dispatch(toggleTodo(id))
}
}

const TodoList = connect(mapStateToProps, mapDispatchToProps)(components.TodoList)

export default TodoList

reducer .js

const reducer = (todos = [], action) => {
switch(action.type) {
case 'ADD_TODO': {
return [...todos, {id: action.id, text: action.text, completed: false}]
}
case 'TOGGLE_TODO': {
return todos.map(todo => todo.id === action.id ? {...todo, completed: !todo.completed} : todo)
}

default: {
return todos
}
}
}

export default reducer

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { TodoList } from './containers'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import reducer from './reducers'


const store = createStore(reducer)

ReactDOM.render(
<Provider store={store}>
<TodoList />
</Provider>,
document.getElementById("app")
)

最佳答案

而不是在这里声明:

mapDispatchToProps = (state) =>

使用调度:

mapDispatchToProps = (dispatch) =>

containers.js中。

DOC:

container components can dispatch actions. In a similar fashion, you can define a function called mapDispatchToProps() that receives the dispatch() method and returns callback props that you want to inject into the presentational component.

关于reactjs - "dispatch"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45953203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com