我有一个组件,它显示一个类别的产品。CategoryId取自订阅方法,它是由pubsub模式形成的,所以我在等待sub函数完成,并将其传递给我的API,但它不能处理页面的初始加载?
import { subscribe } from "./pubsub";
const Test = () => {
const [productId, setProductId] = useState({});
const [response, setResponse] = useState([]);
React.useEffect(() => {
function sub() {
return new Promise((resolve, reject) => {
subscribe("product-message", (data) => {
// console.log("Got some message", data);
// setProductId(data.productId);
resolve(data.productId);
});
});
}
async function fetchData() {
let message = await sub();
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${message.productId}` // Here I couldn't get the async data from above useEffect
);
console.log(response);
setResponse(response);
}
fetchData();
}, []);
return <div>{response.title}</div>; //It is not printing in intial load
};
export default Test;下面是我的沙箱链接:https://codesandbox.io/s/happy-forest-to9pz?file=/src/test.jsx
发布于 2021-03-22 21:53:46
如果您只需要响应,则不需要将productId存储在状态中,然后在另一个useEffeect中使用它来获取数据。您可以在一个useEffec中简单地实现逻辑。还要注意,您需要使用来自fetch call的json响应,因此您需要像这样使用它。
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
).then(res => res.json()); 或
let res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
)
let response = await res.json();完整的函数将如下所示
const Test = () => {
const [response, setResponse] = useState([]);
React.useEffect(() => {
async function fetchData(productId) {
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
).then(res => res.json());
console.log(response);
setResponse(response);
}
console.log("Api calls");
subscribe("product-message", (data) => {
// console.log("Got some message", data);
fetchData(data.productId);
});
}, []);
return <div>{response.title}</div>;
};
export default Test;但是,如果您的应用程序中需要productId,您可以使用多useEffect方法,就像您在沙箱中尝试过的那样。还要确保您正确地使用了fetch调用,并确保不会使API调用productId不可用。
const Test = () => {
const [productId, setProductId] = useState({});
const [response, setResponse] = useState([]);
React.useEffect(() => {
console.log("Api calls");
subscribe("product-message", (data) => {
// console.log("Got some message", data);
setProductId(data.productId);
});
}, []);
React.useEffect(() => {
async function fetchData() {
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}` // Here I couldn't get the async data from above useEffect
);
const response = await res.json();
console.log(response);
setResponse(response);
}
if(productId) {
fetchData();
}
}, [productId]);
return <div>{response.title}</div>;
};
export default Test;https://stackoverflow.com/questions/66747222
复制相似问题