如何使用获取的变量作为材料 UI 日期选择器的初始状态?
Posted
技术标签:
【中文标题】如何使用获取的变量作为材料 UI 日期选择器的初始状态?【英文标题】:How do I use a fetched variable as initial state for material UI datepicker? 【发布时间】:2021-07-12 19:07:52 【问题描述】:我对 Reactjs 还很陌生,我正在尝试为订阅网站建立一个 woocommerce 帐户配置文件。因此,我想将异步获取的订阅的下一个付款日期显示为材料 UI Daypicker 的初始值。但是,我找不到这样做的方法。
我尝试在下一个付款日期使用带有初始值的钩子,但是,状态初始值不能是异步的。如果我选择将状态设置为下一个付款日期,则日期选择器首先设置为当前日期。此外,如果我尝试使用 UseEffect 对其进行更新,则每次尝试将日期选择器更新为新日期时,它都会恢复到初始状态。
将挂钩的初始值设置为订阅的下一个付款日期并可能更新到新日期,我缺少什么?
非常感谢。
import React, useEffect, useState from 'react';
import getSubscription from '../queries/subscriptions';
import Select from 'react-select'
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import DatePicker from '@material-ui/lab/DatePicker';
import TextField from '@material-ui/core/TextField';
const GetSubscription = () =>
const userId = localStorage.getItem('user_id')
const [subscriptions, setSubscriptions] = useState([]);
const [nextDate, setNextDate] = useState();
useEffect(() =>
if (userId)
getSubscription(userId, setSubscriptions)
, [userId]);
const handleClick = (e) =>
setSubscriptions( ...subscriptions, id: e.value, label: e.status )
if (subscriptions.selectOptions)
return (
<div>
<Select options=subscriptions.selectOptions
onChange=handleClick
defaultValue=subscriptions.selectOptions[0]
/>
<LocalizationProvider dateAdapter=AdapterDateFns>
<DatePicker
disablePast
variant="static"
label="Responsive"
openTo="date"
views=['date']
value=nextDate
onChange=(date) => setNextDate(date);
/>
</LocalizationProvider>
</div>
)
else
return <>Aan het laden....</>;
export default GetSubscription
获取订阅功能:
export const getSubscription = async (userId, setSubscriptions) =>
const result = await fetchSubscription(userId)
const data = result?.data || []
const options = data.map(d => (
"value": d.id,
"label": "#" + d.id + " - " + d.billing.first_name + " " + d.billing.last_name,
"billing_interval": d.billing_interval,
"start_date": d.start_date,
"next_payment_date": d.next_payment_date,
"products": d.line_items,
"billing": d.billing,
"shipping": d.shipping,
"price": d.total
))
setSubscriptions(
data: data,
selectOptions: options,
id: data[0].id,
billing_interval: data[0].billing_interval,
start_date: data[0].start_date,
next_payment_date: data[0].next_payment_date,
products: data[0].line_items,
billing: data[0].billing,
shipping: data[0].shipping,
price: data[0].total
)
const fetchSubscription = async (userId) =>
return axios
.get('http://www.localhost//wp-json/wc/v1/subscriptions?customer=' + userId,
headers:
'Content-Type': 'application/json',
Authorization: `Bearer $localStorage.getItem('token')`
)
.catch((err) => console.log(err));
【问题讨论】:
【参考方案1】:可以在状态中设置初始值
const [nextDate, setNextDate] = useState(new Date());
【讨论】:
以上是关于如何使用获取的变量作为材料 UI 日期选择器的初始状态?的主要内容,如果未能解决你的问题,请参考以下文章