gpt4 book ai didi

reactjs - 将 Redux 添加到现有的 React 应用程序

转载 作者:行者123 更新时间:2023-12-03 13:19:39 24 4
gpt4 key购买 nike

我一直在开发一个 React 应用程序,并且已经到了需要 Redux 来处理它的某些方面的地步。

读完一堆教程后,我对如何使我的“更智能”组件变得“更笨”并将函数移至我的操作和 reducer 中相当困惑。

例如,该应用程序的一方面更像是待办事项列表样式。

我的一个类是这样开始的:

export default class ItemList extends React.Component {
constructor() {
super();
this.state = { items: [],
completed: [],
};
this.addItem = this.addItem.bind(this);
this.completeItem = this.completeItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
}

addItem(e) {
var i = this.state.items;
i.push({
text: this._inputElement.value,
paused: false,
key: Date.now()
});
this.setState({ items: i });
e.preventDefault();
this._inputElement.value = '';
this._inputElement.focus();
}

completeItem(e) {
this.deleteItem(e);
var c = this.state.completed;
c.push({
text: e.target.parentNode.parentNode.getElementsByClassName('item-name')[0].innerHTML,
paused: false,
key: Date.now()
});
this.setState({ completed: c });
}

deleteItem(e) {
var i = this.state.items;
var result = i.filter(function(obj) {
return obj.text !== e.target.parentNode.parentNode.getElementsByClassName('item-name')[0].innerHTML;
});
this.setState({ items: result });
}

// ... more irrelevant code here ...

// there's a function called createTasks that renders individual items

render() {
var listItems = this.state.items.map(this.createTasks);

return <div className="item-list">
<form className="form" onSubmit={this.addItem}>
<input ref={(a) => this._inputElement = a}
placeholder="Add new item"
autoFocus />
<button type="submit"></button>
</form>

{listItems}
</div>;
}
}

所以,正如你所看到的,它的逻辑性很强。我开始通过添加 <Provider> 来添加 Redux在我的索引文件中,并制作了一个到目前为止相当空的基本 reducer 文件:

import { combineReducers } from 'redux';

const itemList = (state = {}, action) => {

};

// ... other irrelevant reducers

const rootReducer = combineReducers({
itemList,
// ...
});

export default rootReducer;

...我已经制作了一个 Action 文件,但其中还没有太多内容。

我一直在努力弄清楚:

  • 我见过的大多数操作示例都只是返回某种 JSON,我应该在使用我的组件可以使用的 JSON 的 reducer 中返回什么?
  • 我的组件逻辑有多少是可重用的,还是我应该忘记它?为了尽可能多地重用我编写的代码,最好的方法是什么?

最佳答案

首先你需要了解 redux 如何与 React 配合使用的总体情况。

在此之前,我们首先了解什么是智能组件和dumb组件。

智能组件

  1. 所有代码逻辑都需要在这里处理
  2. 它们也称为容器。
  3. 它们与商店(也称为状态管理)交互以更新您的组件。

dumb组件

  1. 它们只是从您的容器中读取 props 并渲染您的组件
  2. 这只是 UI View ,不应包含任何逻辑。
  3. 所有样式/html/css 都包含在您的愚蠢组件中。

Here这是一篇很棒的文章,如果您仍然有疑问,可以阅读它来了解智能和愚蠢的组件。

好吧,现在让我们尝试了解 redux 是如何工作的:-

  • 您的智能组件(也称为容器)与您的 redux 存储交互
  • 您从容器中触发操作。
  • 您的操作调用您的 API
  • 您的操作结果通过 reducer 更新存储
  • 容器通过 mapStateToProps 函数读取存储,一旦存储中的值发生变化,它就会更新您的组件。

现在让我们考虑一下您的待办事项示例

TodoListContainer.js

class TodoListContainer extends Component {

componentWillMount () {
// fire you action action
}


render () {
return (
<Todos todos=={this.props.todos} />
)
}
}


function mapStateToProps(state) {
const {todos} = state;
return {
todos;
}
}

export default connect(mapStateToProps)(TodoListContainer)

TodoList.js

class TodoList extends Component {

renderTodos() {
return this.props.todos.map((todo)=>{
return <Todo todo={todo} key={todo.id} />
})
}

render () {
return () {
if (this.props.todos.length === 0) {
return <div>No todos</div>
}
return (
<div>
{this.renderTodos()}
</div>
)
}
}
}

export default class TodoList

Todo.js

class Todo extends Component {

render () {
return (
<div>
<span>{this.props.todo.id}</span>
<span>{this.props.todo.name}</span>
</div>
)
}
}

reducer

export default function todos(state={},action) {
switch (action.type) {
case 'RECEIVE_TODOS':
return Object.assign(state,action.todos);
}
}

行动

function fetchTodos() {
return(dispatch) => {
axios.get({
//api details
})
.then((res)=>{
dispatch(receiveTodos(res.todos))
})
.catch((err)=>{
console.warn(err)
})
}
}

function receiveTodos(todos) {
return {
type: 'RECEIVE_TODOS',
todos
}
}

现在,如果您已阅读 redux 文档,您会看到操作返回对象,那么我将如何调用返回函数而不是对象的 api。为此,我使用了 redux thunk,你可以阅读 here .

我给了您一个可以获取待办事项的示例。如果您想执行其他操作,例如deleteTodo、addTodo、modifyTodo,那么您可以在适当的组件中执行此操作。

  1. DeleteTodo - 您可以在 TodoListContainer 中执行。
  2. AddingTodo - 您可以在 TodoListContainer 中执行操作。
  3. 更改状态(已完成/待定) - 您可以在 TodoListContainer 中执行。
  4. ModifyingTodo - 您可以在 TodoContainer 中执行操作。

您还可以查看here详细的例子,但在此之前我想说的是应该先了解一下 redux 的基础知识,你可以找到 here

P.S:我即时编写了代码,因此它可能无法正常工作,但只需稍加修改即可工作。

关于reactjs - 将 Redux 添加到现有的 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43381621/

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