我有一个react函数从axios返回一个promise,我需要对传递给它的方程类型字符串进行编码。
const { equation } = this.state;
axios.post(`${this.state.rootUrl}/integrate`, { equation }).then(some other code)
我想在将字符串方程传递给 API 进行查询之前对其进行编码。
我尝试了以下方法,但没有成功。
axios.post(`${this.state.rootUrl}/integrate`, { encodeURIComponent(equation) })
我也尝试过这个:
const { equation } = this.state;
const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)
这也不起作用。
这是我尝试使用的函数的完整代码:
handleSubmit = (e) => {
e.preventDefault();
const { equation } = this.state;
// const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation })
.then((response) => {
const data = response.data;
this.setState({ data: data });
console.log(equation);
if (data != null) {
this.setState({input: data.response[0]});
}
}
}
最佳答案
在原始示例中,您使用简写语法来设置对象属性 - 以下两行代码是等效的:
{ equation }
{ equation: equation }
你的后两个例子没有做同样的事情!在示例二中,您尝试在方法调用中使用简写,但这是行不通的。在示例三中,您尝试解构 encodeURIComponent(equation)
的返回值,这也不起作用(它返回一个字符串)。
Fawaz 的第一个示例几乎可以工作,但行为上有细微的差别 - 因为他们将变量命名为 test
,传递给 Axios 的对象的键也 进行测试
。请记住,这些是等效的:
{ test }
{ test: test }
据推测,您的 API 需要的是名为 equation
的内容,而不是 test
,因此这不起作用。
为了获得正确的行为,您应该确保您传递的对象具有正确的键:
const test = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation: test })
// or
axios.post(`${this.state.rootUrl}/integrate`, { equation: encodeURIComponent(equation) })
关于javascript - React 中的encodeURIComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48545158/