简体   繁体   English

如何使用Redux在待办事项列表中添加待办事项

[英]How to use redux to add todo item in todo list

I have created action and reducers for my application. 我已经为我的应用程序创建了actionreducers I am trying to create a new todo and want to save it in state using redux . 我正在尝试创建一个新的待办事项,并希望使用redux将其保存为状态。

action/index.js 动作/ index.js

let taskID = 0;

export const addTodo = text => {
  return { type: "ADD_TODO", text, id: taskID++ };
};

reducers/todos.js reducers / todos.js

const todo = (state = {}, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        id: action.id,
        text: action.text,
        status: false
      };
    default:
      return state;
  }
};

export default todo;

reducers/index.js reducers / index.js

import { combineReducers } from "redux";
import todos from "./todos";

const todoApp = combineReducers({ todo });

export default todoApp;

index.js index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import "./index.css";

import { Provider } from "react-redux";
import { createStore } from "redux";
import todoApp from "./reducers/todos";

let store = createStore(todoApp);

ReactDOM.render(
  <Provider store={store}><App /></Provider>,
  document.getElementById("root")
);
registerServiceWorker();

App.js App.js

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

import AppBar from "material-ui/AppBar";
import FloatingActionButton from "material-ui/FloatingActionButton";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import * as strings from "./Strings";
import * as colors from "./Colors";
import styles from "./Styles";
import ContentAdd from "material-ui/svg-icons/content/add";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import * as injectTapEventPlugin from "react-tap-event-plugin";
import TextField from "material-ui/TextField";
import { List, ListItem } from "material-ui/List";
import { connect } from "react";
import { addTodo } from "./actions/index";

const AppBarTest = () =>
  <AppBar
    title={strings.app_name}
    iconClassNameRight="muidocs-icon-navigation-expand-more"
    style={{ backgroundColor: colors.blue_color }}
  />;

class App extends Component {
  constructor(props) {
    injectTapEventPlugin();
    super(props);
    this.state = {
      open: false,
      todos: [],
      notetext: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleOpen = () => {
    this.setState({ open: true });
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  handleCreateNote = () => {
    let todos = [...this.state.todos];
    todos.push({
      id: todos.length,
      text: this.state.notetext,
      completed: false
    });
    this.setState({ todos: todos }, () => {
      // setState is async, so this is callback
    });
    this.handleClose();
  };

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  _renderTodos() {
    return this.state.todos.map(event => {
      return (
        <ListItem
          primaryText={event.text}
          key={event.id}
          style={{ width: "100%", textAlign: "center" }}
          onTouchTap={this._handleListItemClick.bind(this, event)}
        />
      );
    });
  }

  _handleListItemClick(item) {
    console.log(item);
  }

  render() {
    return (
      <MuiThemeProvider>
        <div>
          <AppBarTest />
          <FloatingActionButton
            style={styles.fab}
            backgroundColor={colors.blue_color}
            onTouchTap={this.handleOpen}
          >
            <ContentAdd />
          </FloatingActionButton>
          <Dialog
            open={this.state.open}
            onRequestClose={this.handleClose}
            title={strings.dialog_create_note_title}
          >
            <TextField
              name="notetext"
              hintText="Note"
              style={{ width: "48%", float: "left", height: 48 }}
              defaultValue={this.state.noteVal}
              onChange={this.handleChange}
              onKeyPress={ev => {
                if (ev.key === "Enter") {
                  this.handleCreateNote();
                  ev.preventDefault();
                }
              }}
            />

            <div
              style={{
                width: "4%",
                height: "1",
                float: "left",
                visibility: "hidden"
              }}
            />

            <FlatButton
              label={strings.create_note}
              style={{ width: "48%", height: 48, float: "left" }}
              onTouchTap={this.handleCreateNote}
            />
          </Dialog>

          <List style={{ margin: 8 }}>
            {this._renderTodos()}
          </List>

        </div>
      </MuiThemeProvider>
    );
  }
}

export default App;

I want to save new todo inside handleCreateNote function, I am not sure how to use store, dispatch here to save it in state. 我想在handleCreateNote函数中保存新的待办事项,我不确定如何使用存储,在此处调度以将其保存为状态。 Can anyone help me ? 谁能帮我 ?

Change 更改

export default App; To

function mapStateToProps(state) {
    return {
        todo: todo
    }
}
export default connect(mapStateToProps, actions)(App)

You should also import all the actions using 您还应该使用导入所有动作

import * as actions from './action/index';

After all these modify your this function as follows:- 完成所有这些操作后,按如下所示修改此函数:

handleCreateNote = () => {
    let todos = [...this.state.todos];
    let newTodo = {
      id: todos.length,
      text: this.state.notetext,
      completed: false
    };
    todos.push(newTodo);
    this.setState({ todos: todos }, () => {
      // setState is async, so this is callback
    });
    this.props.addTodo(this.state.notetext);
    this.handleClose();
  };

Also your logic for adding todos is incorrect. 您添加待办事项的逻辑也不正确。 So your action creator should be something like this 所以你的动作创造者应该是这样的

let taskID = 0;

export const addTodo = text => {
  return { 
    type: "ADD_TODO", 
    text: text,
    id: taskId++
  };
};

Now the reducer also needs to change, so that should be something like this:- 现在减速器也需要改变,所以应该是这样的:

const todo = (state = [], action) => {
  switch (action.type) {
    case "ADD_TODO":
      let newTodo = {
        id: action.id,
        text: action.text,
        status: false
      };
      return [...state, newTodo]
    default:
      return state;
  }
};

export default todo;

I hope this helps.Not the best of implementations, but will solve your issue. 我希望这会有所帮助。不是最好的实现,但可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM