我有一个简单的组件,我想根据它的道具进行切换。代码如下:
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;
当我运行此命令并单击所述组件时,控制台将返回event
个对象。我能做些什么来传递一些东西?
请注意我之前使用过onClick={() => { props.toggle(props.id) }}
,但我不认为这是正确的方法。
答案 0 :(得分:2)
mapStateToProps
需要根据道具选择一个待办事项(确切地称为id道具)。您还必须为待办事项创建减速器(复数!)。这个减速器调用单个减速器的减速器。你应该看看标准Redux todo example,它可以完成你需要的一切。
在示例中请注意,有两个reducer,一个用于reducers列表,另一个用于单个reducer。
答案 1 :(得分:1)
reducers.js return isDone
const todoItemReducer = (state = [], action) => {
switch (action.type) {
case 'TODOITEM__TOGGLE_TODO':
console.log(action.id);
return {
isDone: !state.isDone
};
}
return state;
};
export default todoItemReducer;
container.js
import { connect } from 'react-redux';
import component from './component';
import * as actions from './actions';
const mapStateToProps = (state) => {
return {
isDone: state.isDone
};
};
const mapDispatchToProps = (dispatch) => {
return {
toggle: (id) => { dispatch(actions.toggleTodo(id)); }
}
};
const TodoItem = connect(
mapStateToProps, mapDispatchToProps
)(component);
export default TodoItem;
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.bind(this,props.id}>{props.text}</li>
);
}
export default TodoItem;