我正在学习react-redux-rails,方法是为一个简单的待办事项列表构建一个应用程序。我发现自己越来越不清楚redux的某些部分是如何工作的,以及它期望我使用什么。目前,我正在尝试从我的数据库中获取一个待办事项列表,并将它们作为react组件填充。此外,我还在尝试习惯使用功能组件。
我有一个静态页面,它呈现一个带有商店和应用程序组件的Provider
document.addEventListener('DOMContentLoaded', () => {
const container = document.getElementById('root');
const root = ReactDOMClient.createRoot(container)
root.render(
<Root store={store}/>
)
})
然后我有一组Todos的动作
export const RECEIVE_TODOS = "RECEIVE_TODOS"
export const RECEIVE_TODO = "RECEIVE_TODO"
export const REMOVE_TODO = "REMOVE_TODO"
import * as APIUtil from '../util/todo_api_util'
export const receiveTodos = (todos) => {
return {
type: RECEIVE_TODOS,
todos,
}
}
export const receiveTodo = (todo) => {
return {
type: RECEIVE_TODO,
todo,
}
}
export const removeTodo = (todo) => {
return {
type: REMOVE_TODO,
todo,
}
}
export const fetchTodos = () => dispatch => (
APIUtil.fetchTodos().then(todos => dispatch(receiveTodos(todos)))
)
最后一种方法使用thunk中间件(添加到存储中),并从这个简单的API中提取
export const fetchTodos = () => {
return(jQuery.ajax({
method: 'GET',
url: '/api/todos',
}))
}
最后,我有一个TodoList容器
import { connect } from "react-redux";
import { receiveTodo } from "../../actions/todo_actions"
import TodoList from "./todo_list";
import { allTodos } from "../../reducers/selectors";
import { fetchTodos } from "../../util/todo_api_util";
const mapStateToProps = state => ({
todos: allTodos(state)
});
const mapDispatchToProps = dispatch => ({
receiveTodo: (todo) => dispatch(receiveTodo(todo)),
requestTodos: () => dispatch(fetchTodos())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoList);
以及待办事项列表本身
import React, { useEffect } from "react";
import TodoForm from "./todo_form";
import TodoListItem from "./todo_list_item";
const TodoList = (props) => {
console.log(props)
useEffect(() => {
props.requestTodos();
})
return(
<div className="todo-list">
<TodoForm
receiveTodo={ props.receiveTodo } />
<ul className="todo-items">
{props.todos.map((todo, idx) => {
return (
<TodoListItem key={idx} todo={todo}
receiveTodo={ props.receiveTodo} />)
})}
</ul>
</div>
)
}
export default TodoList;
现在我以为我理解了useEffect是componentDidMount的替代,但是当我运行它时,我得到如下错误
我试过用几种方法重新组织它(删除'()',调用store等),但是都不能让它工作。另外,如果我直接在控制台中调用store.dispatch(requestTodos())(所有内容都放在窗口上),它们会更新todos。你知道该怎么做/为什么吗?
1条答案
按热度按时间pgccezyw1#
在进一步研究了功能组件之后,我需要从react-redux导入{ useDispatch }以允许存储更新。我修改了我的待办事项列表组件,现在它可以工作了: