簡體   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