我在我的專案中遇到問題,當我從 datepicker 日歷中選擇日期時會產生錯誤,我實際上想用額外的輸入保存我的資料作為日期,為此我使用來自 mui 的日期選擇器(材料 Ui),但我找不到任何解決方案或無法解決此錯誤。我將展示我的代碼的某些部分,以展示我所面臨的以及我想要解決的問題。
日期選擇器欄位影像
這是日期選擇器日歷的影像,當我單擊其中的任何數字時,它會給我一個錯誤,當我編輯生成的欄位錯誤時也是如此。

單擊任何數字時出錯
生成的錯誤行如下所示,我不明白為什么會這樣。
TypeError: Cannot read properties of undefined (reading 'value')
(anonymous function)
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/src/components/client/index.jsx:182
179 | onChange={(e) => {
180 | setPlanData((prev) => {
181 | return {
> 182 | ...prev, planDate: e.target.value };
| ^ 183 | });
184 | }
185 | }
View compiled
basicStateReducer
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:15195
15192 |
15193 | function basicStateReducer(state, action) {
15194 | // $FlowFixMe: Flow doesn't like mixed types
> 15195 | return typeof action === 'function' ? action(state) : action;
15196 | }
15197 |
15198 | function mountReducer(reducer, initialArg, init) {
View compiled
updateReducer
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:15318
15315 | newState = update.eagerState;
15316 | } else {
15317 | var action = update.action;
> 15318 | newState = reducer(newState, action);
| ^ 15319 | }
15320 | }
15321 |
View compiled
updateState
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:15641
15638 | }
15639 |
15640 | function updateState(initialState) {
> 15641 | return updateReducer(basicStateReducer);
15642 | }
15643 |
15644 | function rerenderState(initialState) {
View compiled
useState
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:16442
16439 | ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
16440 |
16441 | try {
> 16442 | return updateState(initialState);
| ^ 16443 | } finally {
16444 | ReactCurrentDispatcher$1.current = prevDispatcher;
16445 | }
View compiled
useState
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react/cjs/react.development.js:1508
1505 | }
1506 | function useState(initialState) {
1507 | var dispatcher = resolveDispatcher();
> 1508 | return dispatcher.useState(initialState);
1509 | }
1510 | function useReducer(reducer, initialArg, init) {
1511 | var dispatcher = resolveDispatcher();
View compiled
PlanningData
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/src/components/client/index.jsx:80
77 | const [value, setValue] = React.useState(new Date());
78 |
79 |
> 80 | const [plandata, setPlanData] = useState({
| ^ 81 | finishcode: "",
82 | styleName: "",
83 | MON: "",
View compiled
renderWithHooks
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:14985
14982 | }
14983 | }
14984 |
> 14985 | var children = Component(props, secondArg); // Check if there was a render phase update
| ^ 14986 |
14987 | if (didScheduleRenderPhaseUpdateDuringThisPass) {
14988 | // Keep rendering in a loop for as long as render phase updates continue to
View compiled
updateFunctionComponent
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:17356
17353 | {
17354 | ReactCurrentOwner$1.current = workInProgress;
17355 | setIsRendering(true);
> 17356 | nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
| ^ 17357 |
17358 | if ( workInProgress.mode & StrictMode) {
17359 | disableLogs();
View compiled
beginWork
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:19063
19060 | var _Component = workInProgress.type;
19061 | var unresolvedProps = workInProgress.pendingProps;
19062 | var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
> 19063 | return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderLanes);
| ^ 19064 | }
19065 |
19066 | case ClassComponent:
View compiled
HTMLUnknownElement.callCallback
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:3945
3942 | function callCallback() {
3943 | didCall = true;
3944 | restoreAfterDispatch();
> 3945 | func.apply(context, funcArgs);
| ^ 3946 | didError = false;
3947 | } // Create a global error event handler. We use this to capture the value
3948 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:3994
3991 | // errors, it will trigger our global error handler.
3992 |
3993 | evt.initEvent(evtType, false, false);
> 3994 | fakeNode.dispatchEvent(evt);
| ^ 3995 |
3996 | if (windowEventDescriptor) {
3997 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:4056
4053 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
4054 | hasError = false;
4055 | caughtError = null;
> 4056 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
4057 | }
4058 | /**
4059 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
beginWork$1
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:23964
23961 | } // Run beginWork again.
23962 |
23963 |
> 23964 | invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
| ^ 23965 |
23966 | if (hasCaughtError()) {
23967 | var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
View compiled
performUnitOfWork
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:22776
22773 |
22774 | if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
22775 | startProfilerTimer(unitOfWork);
> 22776 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
| ^ 22777 | stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22778 | } else {
22779 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
View compiled
workLoopSync
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:22707
22704 | function workLoopSync() {
22705 | // Already timed out, so perform work without checking if we need to yield.
22706 | while (workInProgress !== null) {
> 22707 | performUnitOfWork(workInProgress);
22708 | }
22709 | }
22710 |
View compiled
renderRootSync
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:22670
22667 |
22668 | do {
22669 | try {
> 22670 | workLoopSync();
| ^ 22671 | break;
22672 | } catch (thrownValue) {
22673 | handleError(root, thrownValue);
View compiled
performSyncWorkOnRoot
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:22293
22290 | }
22291 | } else {
22292 | lanes = getNextLanes(root, NoLanes);
> 22293 | exitStatus = renderRootSync(root, lanes);
| ^ 22294 | }
22295 |
22296 | if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
View compiled
(anonymous function)
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:11327
11324 | var callback = _queue[i];
11325 |
11326 | do {
> 11327 | callback = callback(_isSync2);
| ^ 11328 | } while (callback !== null);
11329 | }
11330 | });
View compiled
unstable_runWithPriority
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/scheduler/cjs/scheduler.development.js:468
465 | currentPriorityLevel = priorityLevel;
466 |
467 | try {
> 468 | return eventHandler();
| ^ 469 | } finally {
470 | currentPriorityLevel = previousPriorityLevel;
471 | }
View compiled
runWithPriority$1
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:11276
11273 |
11274 | function runWithPriority$1(reactPriorityLevel, fn) {
11275 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
> 11276 | return Scheduler_runWithPriority(priorityLevel, fn);
11277 | }
11278 | function scheduleCallback(reactPriorityLevel, callback, options) {
11279 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
View compiled
flushSyncCallbackQueueImpl
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:11322
11319 | try {
11320 | var _isSync2 = true;
11321 | var _queue = syncQueue;
> 11322 | runWithPriority$1(ImmediatePriority$1, function () {
| ^ 11323 | for (; i < _queue.length; i ) {
11324 | var callback = _queue[i];
11325 |
View compiled
flushSyncCallbackQueue
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:11309
11306 | Scheduler_cancelCallback(node);
11307 | }
11308 |
> 11309 | flushSyncCallbackQueueImpl();
11310 | }
11311 |
11312 | function flushSyncCallbackQueueImpl() {
View compiled
discreteUpdates$1
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:22420
22417 | if (executionContext === NoContext) {
22418 | // Flush the immediate callbacks that were scheduled during this batch
22419 | resetRenderTimer();
> 22420 | flushSyncCallbackQueue();
| ^ 22421 | }
22422 | }
22423 | }
View compiled
discreteUpdates
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:3756
3753 | isInsideEventHandler = true;
3754 |
3755 | try {
> 3756 | return discreteUpdatesImpl(fn, a, b, c, d);
| ^ 3757 | } finally {
3758 | isInsideEventHandler = prevIsInsideEventHandler;
3759 |
View compiled
dispatchDiscreteEvent
C:/Users/Awais Bin Riaz/Desktop/React/Web-Development-Class/table-react/web/node_modules/react-dom/cjs/react-dom.development.js:5889
5886 | flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
5887 | }
5888 |
> 5889 | discreteUpdates(dispatchEvent, domEventName, eventSystemFlags, container, nativeEvent);
5890 | }
5891 |
5892 | function dispatchUserBlockingUpdate(domEventName, eventSystemFlags, container, nativeEvent) {
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message.
服務器代碼
這是我的服務器代碼,這里是資料模式,api撰寫。
import express from 'express'
import mongoose from "mongoose"
import cors from "cors"
import path from "path";
import { createServer } from "http";
import { Server } from "socket.io";
import {
stringToHash,
varifyHash
} from "bcrypt-inzi"
import jwt from 'jsonwebtoken';
import cookieParser from 'cookie-parser';
import postmark from "postmark"
const __dirname = path.resolve();
// making some environment setting
const SECRET = process.env.SECRET
const POSTMARK_KEY = process.env.POSTMARK_KEY
const PORT = process.env.PORT
const app = express()
let client = new postmark.ServerClient(POSTMARK_KEY);
// connect mongodb url
mongoose.connect('##############');
// making schema for planning data
const PlanData = mongoose.model("Planning Data", {
created: { type: Date, default: Date.now },
finishcode: String,
styleName: String,
MON: String,
division: String,
orderQuantity: String,
barcode: String,
customer: String,
orderStatus: String,
planQuantity: String,
planDate: String,
})
app.use(express.json())
app.use(cookieParser())
app.use(cors({
origin: true,
credentials: true
}))
app.use('/', express.static(path.join(__dirname, 'web/build')))
app.get("/", (req, res, next) => {
res.sendFile(path.join(__dirname, "./web/build/index.html"))
})
app.get("/api/v1/gellAllPlanData", (req, res) => {
PlanData.find({})
.sort({ _id: "desc" })
.exec(function (err, data) {
res.send(data);
});
});
app.get("/api/v1/plandata", (req, res) => {
PlanData.findOne({})
.sort({ _id: "desc" })
.exec(function (err, data) {
res.send(data);
});
});
app.post("/api/v1/plandata", (req, res) => {
PlanData.findOne({ finishcode: req.body.finishcode, MON: req.body.MON }, (err, data) => {
if (data) {
res.send('On this finishcode: MON already exist');
console.log(data)
} else {
const newPlanData = new PlanData({
finishcode: req.body.finishcode,
styleName: req.body.styleName,
MON: req.body.MON,
division: req.body.division,
orderQuantity: req.body.orderQuantity,
barcode: req.body.barcode,
customer: req.body.customer,
orderStatus: req.body.orderStatus,
planQuantity: req.body.planQuantity,
planDate: req.body.planDate,
});
newPlanData.save().then(() => {
console.log("Planning Data created");
io.emit("PLANDATA", {
finishcode: req.body.finishcode,
styleName: req.body.styleName,
MON: req.body.MON,
division: req.body.division,
orderQuantity: req.body.orderQuantity,
barcode: req.body.barcode,
customer: req.body.customer,
orderStatus: req.body.orderStatus,
planQuantity: req.body.planQuantity,
planDate: req.body.planDate,
});
res.send("Planning Data created");
});
}
});
});
app.put("/api/v1/plandata", (req, res) => {
PlanData.updateOne({
_id: req.body.id
}, {
finishcode: req.body.finishcode,
styleName: req.body.styleName,
MON: req.body.MON,
division: req.body.division,
orderQuantity: req.body.orderQuantity,
barcode: req.body.barcode,
customer: req.body.customer,
orderStatus: req.body.orderStatus,
planQuantity: req.body.planQuantity,
planDate: req.body.planDate,
}, (err, data) => {
res.send("Data Edited");
});
});
app.delete("/api/v1/plandata", (req, res) => {
Post.deleteOne({ _id: req.body.id}, (err, data) => {
res.send("Data deleted");
});
});
app.get("/**", (req, res, next) => {
res.sendFile(path.join(__dirname, "./web/build/index.html"))
})
const server = createServer(app);
const io = new Server(server, { cors: { origin: "", methods: "", } });
io.on("connection", (socket) => {
console.log("New client connected with id: ", socket.id);
socket.emit("topic 1", "some data")
socket.on("disconnect", (message) => {
console.log("Client disconnected with id: ", message);
});
});
server.listen(PORT, function () {
console.log("server is running on", PORT);
})
反應用戶界面代碼
這是我用于專案的 React Js 代碼
import * as React from 'react';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import { Container, InputLabel, MenuItem, Select } from "@mui/material";
import { styled } from '@mui/material/styles';
import FormControl from '@mui/material/FormControl';
import NativeSelect from '@mui/material/NativeSelect';
import InputBase from '@mui/material/InputBase';
import Box from '@mui/material/Box';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DatePicker from '@mui/lab/DatePicker';
import MobileDatePicker from '@mui/lab/MobileDatePicker';
import DesktopDatePicker from '@mui/lab/DesktopDatePicker';
import Stack from '@mui/material/Stack';
import axios from "axios";
import "./index.css";
import { orderStatus, divisions, customers, articles } from "./data";
import backgroundImage from "./../../img/loginbg.jpg";
import { useState, useEffect, useRef } from "react";
import { baseUrl } from "../../core";
import io from "socket.io-client";
function PlanningData() {
const BootstrapInput = styled(InputBase)(({ theme }) => ({
'label &': {
marginTop: theme.spacing(3),
},
'& .MuiInputBase-input': {
borderRadius: 4,
position: 'relative',
backgroundColor: theme.palette.background.paper,
border: '1px solid #ced4da',
fontSize: 16,
padding: '10px 26px 10px 12px',
transition: theme.transitions.create(['border-color', 'box-shadow']),
// Use the system font instead of the default Roboto font.
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:focus': {
borderRadius: 4,
borderColor: '#80bdff',
boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
},
},
}));
const [allPlanData, setAllPlanData] = useState([]);
const [value, setValue] = React.useState(new Date());
const [plandata, setPlanData] = useState({
finishcode: "",
styleName: "",
MON: "",
division: "",
orderQuantity: "",
barcode: "",
customer: "",
orderStatus: "",
planQuantity: "",
planDate: "",
});
useEffect(() => {
axios.get(`${baseUrl}/api/v1/gellAllPlanData`).then((res) => {
console.log("gellAllPlanData: ", res.data);
setAllPlanData(res.data);
});
}, []);
useEffect(() => {
axios
.get(`${baseUrl}/api/v1/plandata`)
.then((res) => {
console.log("res : ", res.data);
setPlanData(res.data);
});
}, []);
const submit = (e) => {
e.preventDefault();
axios
.post(
`${baseUrl}/api/v1/plandata`,
{
finishcode: plandata.finishcode,
styleName: plandata.styleName,
MON: plandata.MON,
division: plandata.division,
orderQuantity: plandata.orderQuantity,
barcode: plandata.barcode,
customer: plandata.customer,
orderStatus: plandata.orderStatus,
planQuantity: plandata.planQuantity,
planDate: plandata.planDate,
}
)
.then((res) => {
console.log("res: ", res.data);
});
};
return (
<div>
<br />
<h1> Planning Data </h1>
<form onSubmit={submit}>
<FormControl sx={{ m: 2.5 }} variant="standard">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="For desktop"
value={plandata.planDate}
minDate={new Date('2017-01-01')}
onChange={(e) => {
setPlanData((prev) => {
return {
...prev, planDate: e.target.value };
});
}
}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</FormControl>
<Button
sx={{ m: 2.5 }}
style={{
display: "inline-block",
padding: "8px",
}}
type="submit"
size="medium"
variant="contained"
color="primary"
>
Add
</Button>
</form>
</div>
);
}
export default PlanningData;
uj5u.com熱心網友回復:
剛看了檔案。看起來 DatePicker 不包含 e.target.value 而是使用函式呼叫來回傳值。
const handleChange = (newValue) => {
setPlanData((prev) => {
return {
...prev, planDate: newValue };
});
};
<DesktopDatePicker
label="For desktop"
value={plandata.planDate}
minDate={new Date('2017-01-01')}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409210.html
標籤:
上一篇:設定cron或任何其他js調度程式來安排整個月的作業,日期之間和不同時間有間隔
下一篇:表示接收字串而不是布林值
