繁体   English   中英

能够从 redux 存储中获取更新的 state 但无法从接收器组件访问更新的 state 中的对象

[英]Able to get the updated state from redux store but not able to access the objects inside the updated state from the receiver component

我正在使用 react 创建一个简单的书单应用程序,并使用 redux 管理 state。 我只有 2 个处理 state 的组件,输入组件调度动作和有效负载,而 output 组件应该获得更新的 state 数据。 使用 output 组件内的 useSelector() 挂钩,我可以看到 state 已更新,但是,当我尝试访问对象数组和长度属性时,我得到“无法读取未定义的属性”。 请让我知道我在这里错过了什么。

这是我的输入组件代码

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import styles from "./Input.module.css";

const Input = () => {
  const dispatch = useDispatch();

  const [bookObject, setBookObject] = useState({
    bookName: "",
    authorName: "",
  });

  const inputChangeHandler = (e) => {
    if (e.target.id === "bookName" || e.target.id === "authorName") {
      setBookObject({
        bookName: document.getElementById("bookName").value,
        authorName: document.getElementById("authorName").value,
      });
    }
  };

  const submitHandler = (e) => {
    if (bookObject.bookName !== "" && bookObject.authorName !== "") {
      dispatch({
        type: "GET_INPUT",
        payload: {
          name: bookObject.bookName,
          author: bookObject.authorName,
          id: Math.random(),
        },
      });
      setBookObject({ bookName: "", authorName: "" });
    } else {
      alert("Enter valid Details");
    }
    e.preventDefault();
  };

  return (
    <form className={styles.form} onSubmit={submitHandler}>
      <div>
        <label>Book's Name</label>
        <input
          id="bookName"
          type="text"
          placeholder="Enter the book's name"
          onChange={inputChangeHandler}
          value={bookObject.bookName}
        />
      </div>
      <div>
        <label>Author's Name</label>
        <input
          id="authorName"
          type="text"
          placeholder="Enter the Author's name"
          onChange={inputChangeHandler}
          value={bookObject.authorName}
        />
      </div>
      <button>Submit</button>
    </form>
  );
};

export default Input;

这是 Output 组件的代码

import React, { Fragment } from "react";
import styles from "./Output.module.css";
import { useSelector } from "react-redux";

const Output = () => {
  
  const outputState = useSelector((state) => state);
  const length = outputState.length
  const outputObj = outputState.outputObj

  return (
    <Fragment>
      {length !== undefined ? (
        <div className={styles.div}>
          <h4>Book List</h4>
          <ul>
            {outputObj.map((book) => (
              <li key={book.id}>
                {book.name}, written by {book.author}
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <h4>The Book List is empty</h4>
      )}
    </Fragment>
  );
};

当我控制台记录 outputState 时,我得到了一个正确的 object 与 outputObj 数组和一个长度属性,但是当我尝试访问 outputState.outputObj 或 outputState.length 时,我得到了提到的错误。 我也尝试过使用两个 useSelector 分别获取数据,但徒劳无功。

这是reducer的代码

import { createStore } from "redux";

const defaultState = {
  outputObj: [],
  length: undefined,
};

const bookListReducer = (state = defaultState, action) => {
  if (action.type === "GET_INPUT") {
    state.outputObj = [...state.outputObj, action.payload];
    return {
      outputObj: state.outputObj,
      length: state.outputObj.length,
    };
  }
};

const store = createStore(bookListReducer);

export default store;

如果没有操作,或者您的操作类型不是“GET_INPUT”,您的减速器将返回未定义,因此 state 将被刷新。 如下更新您的代码。

const bookListReducer = (state = defaultState, action) => {
  if (action.type === "GET_INPUT") {
    state.outputObj = [...state.outputObj, action.payload];
    return {
      outputObj: state.outputObj,
      length: state.outputObj.length,
    };
  }

  return state; // <- HERE
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM