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" }).那么,为什么它不把它推到该州呢?

推荐答案

如果未指定,则button元素默认为type="submit".这里的问题是提交了form元素,并且没有阻止默认表单操作.结果是页面重新加载,例如,Reaction应用程序被重新挂载,所有状态都是初始状态.

onSubmit处理程序移动到form元素,并在onSubmit事件对象上调用preventDefault.此外,强烈建议使用显式的属性,在button元素的基础上加上type="submit".

function AddPostForm() {
  const dispatch = useDispatch();

  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  function onSubmit(event) {
    event.preventDefault(); // <-- prevent form submission, don't reload page

    if (title && content) {
      dispatch(postAdded({ title, content }));
      setTitle('');
      setContent('');
    }
  }

  return (
    <section>
      <h2>Add New Post</h2>
      <form onSubmit={onSubmit}> // <-- onSubmit on form element
        <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 type="submit"> // <-- explicit button type
          Save Post
        </button>
      </form>
    </section>
  );
}
import { createSlice, nanoid } from '@reduxjs/toolkit';

...

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    postAdded: {
      reducer: (state, action) => {
        state.push(action.payload);
      },
      prepare: (payload) => ({
        payload: {
          ...payload,
          id: nanoid();
        },
      })
    },
  },
});

Javascript相关问答推荐

仅在React和JS中生成深色

通过在页面上滚动来移动滚动条

字节数组通过echo框架传输到JS blob

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

在JavaScript中声明自定义内置元素不起作用

扫描qr code后出错whatter—web.js

Next.js(react)使用moment或不使用日期和时间格式

如何在mongoose中链接两个模型?

保持物品顺序的可变大小物品分配到平衡组的算法

在不删除代码的情况下禁用Java弹出功能WordPress

AJAX POST在控制器中返回空(ASP.NET MVC)

FireBase云函数-函数外部的ENV变量

是否可以将异步调用与useState(UnctionName)一起使用

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

在范围数组中查找公共(包含)范围

如何在加载页面时使锚定标记成为焦点

使用静态函数保存 node 前的钩子