我想从其他脚本中获取变量,以根据这些数据构建页面的下一部分。
这是从 API 获取数据的代码:
import Axios from "axios";
import React from "react";
export default class PersonList extends React.Component {
state = {
dataURL: [], //from this variable I want get data
};
componentDidMount() {
Axios.get(
"https://g.tenor.com/v1/search?q=" +
"mems" +
"&key=" +
"MY_TENOR_API_KEY" +
"&limit=" +
"1"
).then((res) => {
this.state.dataURL = res.data;
this.setState({ dataURL });
console.log(this.state.dataURL);
});
}
render() {
return;
}
}
在这里我想动态导入脚本并尝试从其他脚本访问变量
import { useState } from "react";
import styles from "../styles/Form.module.scss";
function Form() {
const [results, setResults] = useState();
return (
<div className={styles.container}>
<div className={styles.form}>
<input
type="button"
onClick={async (e) => {
const { value } = e.currentTarget;
const Fuse = (await import("../pages/api/tenor")).default;
const fuse = new Fuse(state); //I got there an error: "Cannot find name 'state'.ts(2304)"
setResults(fuse.search(value));
}}
/>
</div>
</div>
);
}
export default Form;
回答1
基本上,如果您想从不同的组件访问组件的数据,您可以选择几个选项。
将该数据作为 prop.
发送(仅当第二个组件是第一个组件的子/孙子/等时才相关)管理“全局状态”(包含应用相关数据的单一来源)。
这可以通过第三方库(https://react-redux.js.org/ / https://mobx.js.org/README.html / etc..)
甚至通过 React 的内置 https://reactjs.org/docs/context.html。使用包含状态的共享挂钩,然后可以从其他组件访问该状态。
(仅与功能组件相关)
IMO,最简单的选项是第 3 个,但它需要将 PersonList
变成一个功能挂钩。
示例应如下所示:
// Shared "PersonList" hook.
import Axios from "axios";
import React, { useState } from "react";
export function usePersonList() {
const [dataURL, setDataURL] = useState([]);
useEffect(() => {
Axios.get(
"https://g.tenor.com/v1/search?q=" +
"mems" +
"&key=" +
"MY_TENOR_API_KEY" +
"&limit=" +
"1"
).then(res => setDataURL(res.data));
}, []);
return dataURL;
}
// Form.tsx
import { useState } from "react";
import styles from "../styles/Form.module.scss";
function Form() {
const [results, setResults] = useState();
const dataURL = usePersonList();
return (
<div className={styles.container}>
<div className={styles.form}>
<input
type="button"
onClick={async (e) => {
const { value } = e.currentTarget;
const Fuse = (await import("../pages/api/tenor")).default;
const fuse = new Fuse(dataURL);
setResults(fuse.search(value));
}}
/>
</div>
</div>
);
}
export default Form;
回答2
您可以尝试 https://react-redux.js.org/ 或 https://www.w3schools.com/react/react_usereducer.asp 在组件之间共享变量。