在分配了useState值之后,但得到了未定义的值?

huangapple go评论75阅读模式
英文:

After assign useState values but got undefined?

问题

我在一个 useState 中分配了多个对象,然后使用 Redux Toolkit 从数据库获取数据,然后为这些对象定义了值,但是当我使用 console.log 时,它显示一个状态值未定义,但 console.log 数据库中获取的数据成功。

这是代码

const { data } = useGetConfigQuery();

console.log(data);
console.log(data?.mailgun_api_key);

const configData = {
    mailgun_api_key: data?.mailgun_api_key,
    mailgun_username: data?.mailgun_username,
    mailgun_url: data?.mailgun_url,
    email_id_for_mail_sent: data?.email_id_for_mail_sent,
    isDiscountAvailable: data?.isDiscountAvailable,
    discounted_amount: data?.discounted_amount,
    min_amount_scheme_started: data?.min_amount_scheme_started,
    max_amount_scheme: data?.max_amount_scheme,
    razorpay_key: data?.razorpay_key,
    razorpay_secret: data?.razorpay_secret,
    razorpay_company_name: data?.razorpay_company_name,
};

const [edit, setEdit] = useState(false);
const [config, setConfig] = useState(configData);

console.log(config.mailgun_api_key);

console.log(config);

const handleChange = (e) => {
    setConfig({ ...config, [e.target.name]: e.target.value });
};

Redux 部分

export const configApiSlice = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
        getConfig: builder.query({
            query: () => ({
                url: `${CONFIG_API_URL}`,
                method: "GET",
            }),
            keepUnusedDataFor: 5,
            providesTags: ["Configuration"],
        }),
        updateConfig: builder.mutation({
            query: (data) => ({
                url: `${CONFIG_API_URL}`,
                method: "PUT",
                body: data,
                credentials: "include",
            }),
            invalidatesTags: ["Configuration"],
        }),
    }),
});
英文:

I assign multiple objects in one useState and then fetch the data from the database using the redux toolkit and then defined values for those objects but when I do console.log it shows me a state value is undefined but console.log the fetch data from the database is successful.

here is the code

const { data } = useGetConfigQuery();

	console.log(data);
	console.log(data?.mailgun_api_key);

	const configData = {
		mailgun_api_key: data?.mailgun_api_key,
		mailgun_username: data?.mailgun_username,
		mailgun_url: data?.mailgun_url,
		email_id_for_mail_sent: data?.email_id_for_mail_sent,
		isDiscountAvailable: data?.isDiscountAvailable,
		discounted_amount: data?.discounted_amount,
		min_amount_scheme_started: data?.min_amount_scheme_started,
		max_amount_scheme: data?.max_amount_scheme,
		razorpay_key: data?.razorpay_key,
		razorpay_secret: data?.razorpay_secret,
		razorpay_company_name: data?.razorpay_company_name,
	};

	const [edit, setEdit] = useState(false);
	const [config, setConfig] = useState(configData);

	console.log(config.mailgun_api_key);

	console.log(config);

	const handleChange = (e) => {
		setConfig({ ...config, [e.target.name]: e.target.value });
	};

the redux part

export const configApiSlice = apiSlice.injectEndpoints({
	endpoints: (builder) => ({
		getConfig: builder.query({
			query: () => ({
				url: `${CONFIG_API_URL}`,
				method: "GET",
			}),
			keepUnusedDataFor: 5,
			providesTags: ["Configuration"],
		}),
		updateConfig: builder.mutation({
			query: (data) => ({
				url: `${CONFIG_API_URL}`,
				method: "PUT",
				body: data,
				credentials: "include",
			}),
			invalidatesTags: ["Configuration"],
		}),
	}),
});

答案1

得分: 1

当你最初定义configData时,来自useGetConfigQuery()的数据对象可能尚未填充,因此值将为undefined。

import { useGetConfigQuery } from 'path/to/your/apiSlice'; // 导入查询钩子

const MyComponent = () => {
  const { data, isLoading } = useGetConfigQuery(); // 检索数据和加载状态

  const configData = {
    mailgun_api_key: data?.mailgun_api_key,
    mailgun_username: data?.mailgun_username,
    // ... 其他属性
  };

  const [edit, setEdit] = useState(false);
  const [config, setConfig] = useState(configData);

  useEffect(() => {
    // 当数据发生变化时更新config状态
    setConfig(configData);
  }, [data]);

  const handleChange = (e) => {
    setConfig({ ...config, [e.target.name]: e.target.value });
  };

  // 在获取数据时呈现加载状态
  if (isLoading) {
    return <div>Loading...</div>;
  }

  console.log(config.mailgun_api_key);
  console.log(config);

  return (
    <div>
      {/* 在这里呈现你的组件UI */}
    </div>
  );
};

export default MyComponent;
英文:

When you initially define configData, the data object from useGetConfigQuery() might not have been populated yet, so the values will be undefined.

import { useGetConfigQuery } from &#39;path/to/your/apiSlice&#39;; // Import the query hook

const MyComponent = () =&gt; {
  const { data, isLoading } = useGetConfigQuery(); // Retrieve the data and loading state

  const configData = {
    mailgun_api_key: data?.mailgun_api_key,
    mailgun_username: data?.mailgun_username,
    // ... other properties
  };

  const [edit, setEdit] = useState(false);
  const [config, setConfig] = useState(configData);

  useEffect(() =&gt; {
    // Update the config state when the data changes
    setConfig(configData);
  }, [data]);

  const handleChange = (e) =&gt; {
    setConfig({ ...config, [e.target.name]: e.target.value });
  };

  // Render loading state while fetching data
  if (isLoading) {
    return &lt;div&gt;Loading...&lt;/div&gt;;
  }

  console.log(config.mailgun_api_key);
  console.log(config);

  return (
    &lt;div&gt;
      {/* Render your component UI here */}
    &lt;/div&gt;
  );
};

export default MyComponent;

huangapple
  • 本文由 发表于 2023年6月22日 12:44:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定