import React from 'react';
import { connect } from 'react-redux';
import { RootState, Item } from '../redux/state';
import { addItem, deleteItem, RootDispatch } from '../redux/action';
type Props = {
author: string,
items: Item[],
handleAddItem: (newItemText: string) => void,
handleDeleteItem: (targetId: number) => void
}
class TodoList extends React.Components<Props, {}> {
constructor(props: Props) {
super(props);
// ...
}
// using redux dispatcher
addItem(text: string) {
this.props.handleAddItem(text);
}
render() {
return (
<>
<button onClick={() => this.addItem('123')}>Add item</button>
// using redux state
{this.props.items.map(item => return <p>item.name</p>)}
</>
)
}
}
const mapStateToProps = (state: RootState) => {
return {
author: state.author,
items: state.items
}
}
const mapDispatchToProps = (dispatch: RootDispatch) => {
return {
handleAddItem: (newItemText: string) => {
dispatch(addItem(newItemText));
},
handleDeleteItem: (targetId: number) => {
dispatch(deleteItem(targetId));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter