App.js:
function App() {
return (
<main>
<AddPostForm />
<PostList />
</main>
);
}
字符串
store.js:
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
reducer是push
ing到状态,但在我添加一个测试帖子后(通过表单),我没有看到添加的表单。然而console.log(action.payload)
确实显示了对象(例如Object { id: "rTuWGH9pfK-cQvCZecSvt", title: "asd", content: "asd" }
)。那么为什么它没有将其推入状态?
1条答案
按热度按时间bqf10yzr1#
如果未指定,
button
元素默认为type="submit"
。这里的问题是,form
元素被提交,并且默认表单操作未被阻止。结果是页面重新加载,例如React应用被重新挂载,所有状态都是初始状态。将
onSubmit
处理程序移动到form
元素,并在onSubmit
事件对象上调用preventDefault
。此外,最好显式地使用属性,将type="submit"
添加到button
元素。个字符