App.js:
function App() {
return (
<main>
<AddPostForm />
<PostList />
</main>
);
}
_
export const store = configureStore({
reducer: {
posts: postsReducer
}
})
PostSlice.js:
const initialState = [
{ id: 1, title: 'Learning Redux Toolkit', content: 'I have heard good things.' },
{ id: 2, title: 'Slices...', content: 'The more I say slice, the more I want pizza.' }
];
const postsSlice = createSlice({
name: 'posts',
initialState,
reducers: {
postAdded: (state, action) => {
console.log(action.payload)
state.push(action.payload);
}
}
});
export const selectAllPosts = state => state.posts;
export const { postAdded } = postsSlice.actions;
export default postsSlice.reducer;
AddPostForm.js:
function AddPostForm() {
const dispatch = useDispatch();
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
function onSubmit() {
if (title && content) {
console.log('after if');
dispatch(postAdded({
id: nanoid(),
title,
content
}));
setTitle('');
setContent('');
}
}
return (
<section onSubmit={onSubmit}>
<h2>Add New Post</h2>
<form>
<label htmlFor="title">Post Title:</label>
<input
type="text"
id="title"
value={title}
onChange={e => setTitle(e.target.value)}
/>
<label htmlFor="content">Content:</label>
<textarea
id="content"
value={content}
onChange={e => setContent(e.target.value)}
/>
<button>Save Post</button>
</form>
</section>
)
}
export default AddPostForm
PostList.js:
function PostList() {
const posts = useSelector(selectAllPosts);
return (
<section>
<h2>Posts</h2>
{posts.map(post => (
<article key={post.id}>
<h3>{post.title}</h3>
<p>{post.content.substring(0, 100)}</p>
</article>
))}
</section>
)
}
export default PostList
postAdded
减速器正在向州push
发送,但在我(通过表单)添加了一个测试帖子后,我看不到添加的表单.然而,console.log(action.payload)
显示的是对象(例如Object { id: "rTuWGH9pfK-cQvCZecSvt", title: "asd", content: "asd" }
).那么,为什么它不把它推到该州呢?