编程语言
首页 > 编程语言> > javascript-React Redux-通过动作传递道具

javascript-React Redux-通过动作传递道具

作者:互联网

我有一个简单的组件,我想根据其道具进行切换.代码如下:

actions.js

const toggleTodo = (id) => {
  return {
    type: 'TODOITEM__TOGGLE_TODO',
    id
  }
};

export {
  toggleTodo
}

component.js

import React from 'react';

const TodoItem = (props) => {
  const completed = props.isDone === true ? 'done' : '';

  return (
    <li className={completed} id={props.id} onClick={props.toggle}>{props.text}</li>
  );
}

export default TodoItem;

container.js

import { connect } from 'react-redux';
import component from './component';
import * as actions from './actions';

const mapStateToProps = (state) => {
  return state;
};

const mapDispatchToProps = (dispatch) => {
  return {
    toggle: (id) => { dispatch(actions.toggleTodo(id)); }
  }
};

const TodoItem = connect(
  mapStateToProps, mapDispatchToProps
)(component);

export default TodoItem;

reducers.js

const todoItemReducer = (state = [], action) => {
  switch (action.type) {
    case 'TODOITEM__TOGGLE_TODO':
      console.log(action.id);
      return state;
  }

  return state;
};

export default todoItemReducer;

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

import TodoItem from './components/TodoItem/container';

import reducers from './reducers';

const store = createStore(reducers, window.devToolsExtension && window.devToolsExtension());

render(
  <Provider store={store}>
    <TodoItem key="1" isDone={false} text="Test" id="1" />
  </Provider>,
  app
);

reducers.js

import { combineReducers } from 'redux';

// Reducers
import todoItemReducer from './components/TodoItem/reducers';

const reducers = combineReducers({
  todoItemReducer
});

export default reducers;

当我运行它并单击所述组件时,控制台将返回一个事件对象.我该怎么办才能在那儿传递一些东西?

请注意,我使用了onClick = {()=> {props.toggle(props.id)}}之前,但我认为这不是正确的方法.

解决方法:

mapStateToProps需要根据道具(确切地说是id道具)选择一个待办事项.您还必须为待办事项创建一个化简器(复数!).该减速器称为单项减速器.您应该查看标准的Redux todo example,它可以满足您的所有需求.

请注意,在示例中有两个化简器,一个用于化简器列表,一个用于单个化简器.

标签:reactjs,redux,react-redux,javascript
来源: https://codeday.me/bug/20191118/2028236.html