action
constant
reducer
store.tsx
Home.tsx
import React, { ReactElement, useState, useEffect, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addBook, deleteBook, saveBooks } from "../../redux/action/book";
interface HomeProps {}
const Home: React.FC<HomeProps> = ({}): ReactElement => {
const nodeRef: any = useRef();
const { bookList } = useSelector((state: any) => state.bookReducer);
const dispatch = useDispatch();
useEffect(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{
id: 0,
name: "三国演义",
},
{
id: 1,
name: "水浒传",
},
{
id: 2,
name: "西游记",
},
{
id: 3,
name: "红楼梦",
},
]);
}, 3000);
}).then((res: any) => {
console.log(res);
dispatch(saveBooks(res));
});
}, []);
const deleteItem = (index: number) => {
console.log(index);
dispatch(deleteBook(index));
};
const toAddBook = () => {
console.log(nodeRef.current.value);
let bookObj = {
name: nodeRef.current.value,
id: bookList.length,
};
dispatch(addBook(bookObj));
};
return (
<div>
Home
<div>
<div>
{bookList.map((item: any, index: number) => (
<div key={index}>
<span key={index}>{item.name}</span>
<button onClick={() => deleteItem(index)}>删除</button>
</div>
))}
</div>
<div>
<input type="text" ref={nodeRef} />
<button onClick={toAddBook}>添加</button>
</div>
</div>
</div>
);
};
export default Home;