使用上下文api进行项目,遇到一个无法理解的错误。
“ TypeError:无法读取未定义的属性'slice'”
// context.js
import React, { useReducer, createContext, useContext } from "react";
import userData from "./data/bond.json";
const initialState = { user: userData, clickedState: [] };
console.log(initialState);
console.log(initialState.user);
function bondReducer(state = initialState, action) {
switch (action.type) {
case "CLICK":
return state.user.filter(bond => bond.id !== action.id);
case "DELETE":
return state.clickedState.filter(item => item.id !== action.id);
default:
throw new Error(`Unhandled action type: ${action.type}`);
}
}
const bondStateContext = createContext();
const bondDispatchContext = createContext();
export function BondProvider({ children }) {
const [state, dispatch] = useReducer(bondReducer, initialState);
return (
<bondStateContext.Provider value={state}>
<bondDispatchContext.Provider value={dispatch}>
{children}
</bondDispatchContext.Provider>
</bondStateContext.Provider>
);
}
export function useBondState() { // I made this to import the function in any component in handy.
const context = useContext(bondStateContext);
if (!context) {
throw new Error(`Cannot find BondProvider`);
}
return context;
}
export function useBondDispatch() {
const context = useContext(bondDispatchContext);
if (!context) {
throw new Error(`Cannot find BondProvider`);
}
return context;
}
将context用于其他组件是context.js。
// bondTable.js
import React, { useState } from "react";
import styled from "styled-components";
import { useBondState, useBondDispatch } from "../bondContext";
import Pagination from "./pagination";
function BondTable() {
const Bonds = useBondState();
console.log(Bonds); // object
console.log(Bonds.user); // Array
// pagination
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(8); //
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = Bonds.user.slice(indexOfFirstPost, indexOfLastPost); // error invoked at this point.
console.log(currentPosts);
// Change pages
const paginate = pageNumber => setCurrentPage(pageNumber);
// map bond's data
const list = currentPosts.map(val => ({
id: val.id,
key: val.product_id,
inBasket: false,
product_code: val.product_code.slice(3) + "호",
origin_principal: val.origin_principal.toLocaleString() + "원",
rate: (val.rate * 100).toFixed(2) + "%",
startAt: val.startAt.slice(0, 10),
issueAt: val.issueAt.slice(0, 10),
period: val.period + "일",
leftTerm: dayCalculate(curDate, curDate)
}));
// Click row
const dispatch = useBondDispatch(); // to use dispatch from context
const clickRow = e => {
dispatch({
type: "CLICK",
id: e.currentTarget.id
});
console.log(e.currentTarget.id); // knowing a row's id that I clicked.
};
return (
<>
<Container>
<TableBox>
<tbody>
{list.map((el, index) => (
<Tr key={index} id={el.id} onClick={clickRow}>
<Td>{el.id}</Td>
<Td>{el.product_code}</Td>
<Td></Td>
<Td>{el.origin_principal}</Td>
<Td>{el.rate}</Td>
<Td>{el.startAt}</Td>
<Td>{el.issueAt}</Td>
<Td>{el.period}</Td>
<Td>{el.leftTerm}</Td>
</Tr>
))}
</tbody>
</TableBox>
<Pagination
postsPerPage={postsPerPage}
totalPosts={Bonds.user.length}
paginate={paginate}
/>
</Container>
</>
);
}
export default BondTable;
页面最初呈现的很好,但是当我单击表格的任何行时, 显示错误(“无法读取未定义的属性'slice'”)。 但是如果我在Context.js中将'initialState'设置为'const initialState = userData' 错误未发生,onClick事件运行良好。 这就是为什么我无法理解错误的原因! :(
请让我知道原因,并指出错误的地方。如果你知道原因...