gpt4 book ai didi

javascript - 第一次使用 redux。如何实现?

转载 作者:行者123 更新时间:2023-12-01 02:29:48 26 4
gpt4 key购买 nike

我正在学习一些 Redux 教程,但仍然无法理解如何将其实现到我现有的组件中。每个教程都有一些不同的方法,我很困惑。我有如下代码,想要使用 Redux 进行状态管理。我假设我需要在reducer中删除this.setState函数和控制状态,但在这种情况下,我实际上如何触发函数handleSubmit?我已经写了reducer、store、dispatch,但是我还需要什么?

import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';

import { createStore } from "redux";
import { Provider } from 'react-redux'

const reducer = (state={errorText: '', open: true}, action) => {
switch(action.type) {
case "CHECK_PASSWORD": {
return state = {...state, open: false};
}
default:
return state;
}
}

const store = createStore(reducer, {
errorText: '',
open:true
});

store.subscribe(() => {
console.log('store change', store.getState())
})

store.dispatch({type: "CHECK_PASSWORD"})

export default class StartDialog extends Component {

handleSubmit = event => {
let password = this.refs.myPasswordValue.input.value;
// Check default password
if(password === "123"){
this.setState({ errorText: '', open: false})
} else if (password !== "123" && password !== "") {
this.setState({ errorText: "Password is incorrect" })
} else if (password === ""){
this.setState({ errorText: "Password is required" })
}
};

render() {
const actions = [ <FlatButton label="Submit" primary={true} onClick={this.handleSubmit} /> ];

return (
<Provider store={store} >
<Dialog title="Welcome to the React App!" actions={actions} modal={true} open={this.state.open} >
<TextField errorText={this.state.errorText}
hintText="Password Field"
floatingLabelText="Password"
type="password"
ref="myPasswordValue" />
</Dialog>
</Provider>
);}}

最佳答案

实际上你不应该采用这种类型的结构,如使用<Provider>在调度操作的同一组件中。意思是我想让你思考亲子关系在哪里Provider将在父级中,所有商店操作和订阅都应在子级中完成。查看 Dan Abramov 关于 Redux 代码结构的讨论,因为 UI 组件中不应包含逻辑,而逻辑应在父组件中进行控制。

当您使用商店中的状态时,则不需要 setState 。事实上,当您需要状态作为某些组件中的隐式数据时,您必须使用 setState 。此外,在调度操作时,您已经描述了 type属性,但没有附加实际有效负载( open ),如 reducer 中所述。

您还可以改进代码结构(以新手视角)-

enter image description here

在index.js中,主要的<Provider>应集成组件以向下面的子组件提供状态。

样本index.js (根)代码就像 -

import React from 'react';
import ReactDOM from 'react-dom';
import store from './store/store';
import TodoApp from './container/todoapp';
import { Provider } from 'react-redux';

const render = () => {
ReactDOM.render(
<Provider store={store}>
<TodoApp />
</Provider>
,document.getElementById('root'));
}

现在商店可供子组件使用。所以现在你可以使用connect()通过 args 直接连接到商店必要的 mapStateToPropsmapDispatchToProps .

todoapp.js的示例文件来自容器文件夹 -

import React from 'react';
import ReactDOM from 'react-dom';
import store from '../store/store';
import Todolist from './components/todolist';
import AddTodo from './components/addtodo';
import Footer from './components/footer';
import { connect } from 'react-redux';

var noteId = 0;

const getVisibleTodos = (todos,filter) => {
switch(filter){
case 'SHOW_ALL' :
return todos;
case 'SHOW_COMPLETED' :
return todos.filter(t => t.completed);
case 'SHOW_ACTIVE' :
return todos.filter(t => !t.completed);
default :
return todos;
}
}

class TodoApp extends React.Component{

render() {
const {todos,visibilityFilter} = this.props;

return(
<div>
<AddTodo onAddClick={this.props.onAddTodoClick} />
<ul>
<Todolist todos={this.props.todos}
onTodoClick ={this.props.onTodoListClick}/>
</ul>
<Footer visibilityFilter={this.props.visibilityFilter}
onFilterClick={this.props.onLinkClick} />
<button onClick = {() => console.log(store.getState())}> Arbitrary Button </button>
</div>
);
}
}

const mapStateToProps = (state) => {
return {
visibilityFilter : state.visibilityFilter,
todos: getVisibleTodos(state.todos,state.visibilityFilter)
}
}

const mapDispatchToProps = (dispacth) => {
return {
onLinkClick : (filter) => {
store.dispatch({type :'SET_VISIBILITY_FILTER',filter});
},
onTodoListClick : (id) => {
store.dispatch({type:'TOGGLE_TODO',id});
},
onAddTodoClick : (text) => {
store.dispatch({type:'ADD_TODO',id : noteId++,text})
}
}
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoApp);

render();

商店将包括 -

 import {createStore, combineReducers} from 'redux';

const todo = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state;
}

return {
...state,
completed: !state.completed
}
default:
return state;
}
}

const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
]
case 'TOGGLE_TODO':
return state.map(t => todo(t, action));
default:
return state;
}
}

const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch(action.type){
case 'SET_VISIBILITY_FILTER' :
return action.filter;
default :
return state;
}
}


const todoApp = combineReducers({ todos,visibilityFilter })

const store = createStore(todoApp);
console.log(store.getState());

export default store;

如果您想实现更复杂的项目结构,必须升级当前项目,请检查此代码结构 - https://github.com/react-boilerplate/react-boilerplate

关于javascript - 第一次使用 redux。如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398235/

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