2 回答

TA貢獻1827條經驗 獲得超8個贊
CLEAR_ARRAY_TODOS不是動作,只是一個保存動作類型字符串的變量。你應該添加一個clearTodos動作
export const clearTodos = { type: CLEAR_ARRAY_TODOS }
或動作創建者
export const clearTodos = () => ({ type: CLEAR_ARRAY_TODOS })
并在您的組件中使用它mapDispatchToProps(就像使用getTodos)
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos, clearTodos} from '../.././actions';
class Todos extends Component {
componentDidMount() {
this.props.getTodos();
}
render() {
return (
<div>
<button onClick={ this.props.clearTodos }>Clear array Todos</button>
<ul>
{this.props.todos.map(todo => {
return <li key={todo.id}>
{todo.title}
</li>
})}
</ul>
</div>
);
}
}
const mapStateToProps = state => {
console.log(state.todos);
console.log(state.todo);
const { todos } = state;
return {
todos
};
};
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos()),
clearTodos: () => dispatch(clearTodos())
});
export default connect(mapStateToProps, mapDispatchToProps)(Todos);

TA貢獻1829條經驗 獲得超7個贊
只需將 clearTodos 操作添加到 mapDispatchToProps
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos()),
clearTodos: () => dispatch({type: CLEAR_ARRAY_TODOS})
});
然后你只需要在按鈕被點擊時處理這個動作,所以onClick在那里添加屬性:
<button onClick={this.props.clearTodos}>Clear array Todos</button>
添加回答
舉報