我面临这个问题。当我有一个 Axios 调用时,它承诺调度一个操作来更新 redux 并执行回调。但是当执行回调时,redux 状态似乎已经过时了。
如果单击 getNewDate 按钮,控制台将显示 redux 状态的差异。当 redux 导致重新渲染时,状态将是正确的。
如何在回调期间获得正确的 redux 状态?
这是基于本课程的练习 2.14 https://fullstackopen.com/en/part2/getting_data_from_server。
\n\n用户可以选择一个国家,然后就会显示该国家首都的天气信息。我的代码给出错误无法读取未定义的属性“温度”
\n\nconst Weather = ({ city }) => {\nconst [weatherDetails, setWeatherDetails] = useState([])\n\nuseEffect(() => {\n axios.get(\'http://api.weatherstack.com/current\', {\n params: {\n access_key: process.env.REACT_APP_WEATHER_KEY,\n query: city\n }\n }).then(\n (response) => {\n setWeatherDetails(response.data)\n }\n )\n}, [city])\nconsole.log(\'weather\', weatherDetails);\n\nreturn (\n <div>\n <h3>Weather in {city} </h3>\n {weatherDetails.current.temperature}\n </div>\n)}\nRun Code Online (Sandbox Code Playgroud)\n\n基本上,该行
\n\n{weatherDetails.current.temperature}\nRun Code Online (Sandbox Code Playgroud)\n\n使我的代码崩溃。当我删除该行时,我可以通过 console.log 看到响应,但有两个连续的日志
\n\nweather []\nweather {request: {\xe2\x80\xa6}, location: {\xe2\x80\xa6}, current: {\xe2\x80\xa6}}\nRun Code Online (Sandbox Code Playgroud)\n\n我认为我的代码发生在这两者之间,并且它尝试在数据到达之前访问数据,但我不知道该怎么做才能解决这个问题。
\n\n另外,我不知道 useEffect() 的参数 [city] 是做什么的,所以如果有人能向我解释它的作用那就太好了。
\n\n编辑:解决了!\n将weatherDetail的初始状态设置为null并进行一些条件渲染
\n\nif (weatherDetails) {\n …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的 Nest JS 应用程序中进行第三方 API 调用。由于 Nest JS 在底层使用 Axios,并且在其文档中拥有专门的页面https://docs.nestjs.com/techniques/http-module,因此我确保遵循文档中提供的实现,但我保留当我尝试通过 Nestjs 的 httpModule 发出 HTTP 请求时,遇到httpService undefined错误。我不确定我错过了什么,我尝试在这里搜索相关问题,但没有成功。请帮忙看一下,下面是我的代码示例。
银行验证.service.ts
import { HttpService } from '@nestjs/common';
import { Observable } from 'rxjs';
import { config } from 'dotenv';
import { AxiosResponse } from 'axios';
config();
export class BankVerificationService {
constructor(private httpService: HttpService){}
getBanks(countryCode): Observable<AxiosResponse<any>> {
console.log(this.httpService, '===============')
return this.httpService.get(`https://api.flutterwave.com/v3/banks/${countryCode}`, {
headers: {
Authorization: `Bearer ${process.env.FLUTTERWAVE_TEST_SECRET}`
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的 Axios HTTP 模块配置
import { Module, HttpModule } …Run Code Online (Sandbox Code Playgroud) <template>
<div class="address">
<h1>{{address}}</h1>
</div>
</template>
<script>
export default {
data() {
return {
id: this.$route.params.id,
address:''
}
},
created(){
this.$axios.post("http://localhost/flutter_api/action.php",{
id: this.id,
action: "fetchaddress"
})
.then(function(res) {
console.log(res.data.address); // This returns the address
alert(res.data.address);
this.address=res.data.address;
})
.catch(function(error){
console.log(error)
})
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
它抛出这样的错误 TypeError: Cannot set property 'address' of undefined`` at eval (Address.vue?b0a0:24)
请帮我
我目前正在使用 Nuxt.js 开发一个通用应用程序,大多数页面上的数据是使用 fetch hook 以及 vuex 存储从 API 检索的。我开始注意到页面重新加载/刷新时出现错误,有时当我从导航栏访问页面时出现错误。页面错误为:
TypeError: Cannot read property 'data' of undefined
Run Code Online (Sandbox Code Playgroud)
其中 data 是从 API 检索的对象。我在互联网上搜索了这一点,发现它与数据未加载或页面渲染而数据未完全检索有关。我找到了一种解决方法,在模板上使用 v-if 来检查数据是否已设置,然后显示内容。我的问题是是否有办法实现此目的,我尝试使用 async/await 关键字,但它没有帮助,而且我觉得 v-if 方法不是处理它的最佳方法。
编辑:使用 fetch() 时使用 $fetchState.pending 解决
我正在开发一个使用 axios 和 asp.net core 3.1 作为后端 api 的 React 应用程序(打字稿模板)。例如,我有这个受保护的(JWT 身份)端点来从服务器获取图像文件,如下所示FileStream:
[Authorize(Policy = AspianCorePolicy.AdminAttachmentGetImagePolicy)]
[HttpGet("images/{filename}")]
public async Task<ActionResult> GetImage(string filename)
{
var imageDto = await Mediator.Send(new GetImage.Query { FileName = filename });
return File(imageDto.Memory, imageDto.MimeType, imageDto.FileName);
}
Run Code Online (Sandbox Code Playgroud)
考虑到,我也有一些大的视频文件要流式传输。
img标签中,甚至下载文件,我该如何通过 Axios 和 html 标签来做到这一点video?我应该使用 Axios吗?如果是这样,我到底该怎么做呢?responseType: 'stream'当我的图表组件呈现时,由于其初始状态(在 API 响应之前是一个空数组)而出现错误。它会说类似的内容Cannot read property '0' of undefined,因为当组件加载时,它的初始状态是,嗯......一个空数组。所以我想知道是否有办法让组件仅在收到 API 响应后才渲染。
这是父组件:
function InformationPage({
match: {
params: { symbol },
},
}) {
const [chartData, setChartData] = useState([]); {/*Declaring state*/}
useEffect(() => { {/*Fetching API response here to set state*/}
axios
.get(
`https://finnhub.io/api/v1/stock/candle?symbol=${symbol}&resolution=15&from=1572651390&to=1602623478&token=xxxxxxxxx`
)
.then((res) => {
console.log(res.data);
setChartData(res.data);
})
.catch((err) => {
console.log(err);
});
}, [symbol]);
return (
<Grid item container xs={12} sm={12} md={6} lg={8}>
{chartData && <QuoteChart chartData={chartData} iex={iex} />}
</Grid>
);
}
export Default InformationPage;
Run Code Online (Sandbox Code Playgroud)
这是子图表组件,基本上当我从 …
我正在创建一个注册表单以响应验证。我要求的值是用户名、电子邮件、密码+(控制密码)。有关表单的所有内容、验证、错误,如果您单击“注册”,您将进入一个新页面。现在我想将值提取到我的 MySql 数据库中。我成功地将内容放入数据库中,因此链接有效,但我无法获取我在表单中输入的值。
我努力了
onChange={(e) => {
setUsernameReg(e.target.value);
}}
(see commented item)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这个时,我无法在用户名中填写任何内容。除名称外,其他输入的代码(电子邮件、密码)相同。
简而言之,我想将您在文本框中输入的值获取到我的数据库。
代码:FormSignup.js
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import validate from './validateInfo';
import useForm from './useForm';
import './Form.css';
const FormSignup = ({ submitForm }) => {
const { handleChange, handleSubmit, values, errors } = useForm(
submitForm,
validate
);
const [usernameReg, setUsernameReg] = useState("");
const [emailReg, setEmailReg] = useState("");
const [passwordReg, setPasswordReg] = useState("");
Axios.defaults.withCredentials = true;
const register = () => …Run Code Online (Sandbox Code Playgroud) 我正在使用 axios CDN 链接,但它给出了此错误
Refused to load the script 'https://unpkg.com/axios/dist/axios.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
我正在使用哈巴狗模板引擎。这是我的 base.pug 代码:
doctype html
html
head
meta(charset='UTF-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title Natours |#{title}
link(rel='stylesheet' href='/css/style.css')
link(rel='shortcut icon' type='image/png' href='/img/favicon.png')
link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:300,300i,700')
body
//header
include _header
//content
block content
h1 this is a placeholder
//footer
include _footer
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
script(src='/js/login.js')
Run Code Online (Sandbox Code Playgroud)
这是我的login.js
const login=async (email,password)=>{
try{ …Run Code Online (Sandbox Code Playgroud) 我的后端代码如下,当我使用Laravel 的blade测试它时,它运行良好。但我无法在 React 前端中使用 Axios 执行相同的操作(请参阅下面的前端代码)。
return (new NewsExport())->download($filename);
Run Code Online (Sandbox Code Playgroud)
我以某种方式从另一个站点找到了一些解决方案:他们更改了后端代码,他们使用该Storage方法返回链接而不是文件。但我不想使用Storage,我想防止过度存储文件(以防前端用户快速单击下载按钮)。
我的问题是如何在前端axios中下载后端返回的文件?
我的前端代码(下面的代码成功下载了一个excel文件,但我认为该文件已损坏,因为当我使用Microsoft Excel测试它时无法打开它)
let response = await newsApi.exportNewsList(payload).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'exc.xlsx'); //or any other extension
document.body.appendChild(link);
link.click();
});
Run Code Online (Sandbox Code Playgroud)
这是response.data我登录时的截图:
axios ×10
reactjs ×5
javascript ×4
react-hooks ×2
typescript ×2
vue.js ×2
asp.net-core ×1
c# ×1
fetch ×1
forms ×1
laravel ×1
mysql ×1
nestjs ×1
nuxt.js ×1
pug ×1
redux ×1
rest ×1
vuex ×1