为什么 res.text() 在 useEffect() 中不起作用?

问题描述 投票:0回答:1

islands/test.tsx
我有:

import { useEffect } from "preact/hooks";
export default function Test(){ 
    fetch('https://example.com')
    .then(res => res.text())
    .then(d => console.log(d))
    
    useEffect(() => {        
        fetch('https://example.com')
        .then(res => res.text())
        .then(d => console.log(d))     
    })
    return 'hi'
}

数据在服务器控制台中返回正常,但在客户端控制台中不显示。但是,如果我将

fetch
函数更改为:

fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(d => console.log(d))

然后两边都显示。为什么会这样?

react-hooks client-server fetch-api preact
1个回答
0
投票

区别在于,您在工作示例中调用

res.json()
,在损坏的示例中调用
res.text()

如果您记录响应并查看标题,将会有一个名为

Content-Type
,如果这不包含文本/纯文本,那么您将无法对其调用
res.text()

© www.soinside.com 2019 - 2024. All rights reserved.