may*_*yor 1 javascript reactjs
我有一个从 axios 返回承诺的 React 函数,我需要对传递给它的方程类型字符串进行编码。
const { equation } = this.state;
axios.post(`${this.state.rootUrl}/integrate`, { equation }).then(some other code)
Run Code Online (Sandbox Code Playgroud)
我想在将字符串方程传递给 API 进行查询之前对其进行编码。
我尝试过以下方法,但没有成功。
axios.post(`${this.state.rootUrl}/integrate`, { encodeURIComponent(equation) })
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个:
const { equation } = this.state;
const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)
Run Code Online (Sandbox Code Playgroud)
这也行不通。
这是我尝试使用的函数的完整代码:
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]});
}
}
}
Run Code Online (Sandbox Code Playgroud)
在原始示例中,您使用简写语法来设置对象属性 - 以下两行代码是等效的:
{ equation }
{ equation: equation }
Run Code Online (Sandbox Code Playgroud)
你的第二个例子没有做同样的事情!在示例二中,您尝试在方法调用中使用简写,但这是行不通的。在示例三中,您尝试解构 的返回值encodeURIComponent(equation),这也不起作用(它返回一个字符串)。
Fawaz 的第一个示例几乎可以工作,但行为上有一个微妙的差异 - 因为他们将变量命名为test,所以传递给 Axios 的对象的键也将是test。请记住,这些是等效的:
{ test }
{ test: test }
Run Code Online (Sandbox Code Playgroud)
据推测,您的 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) })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14273 次 |
| 最近记录: |