我有一个function函数,返回来自axios的承诺,我需要编码一个等式类型的字符串被传递给它。
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]});
}
}
}发布于 2018-01-31 15:29:37
在最初的示例中,您使用了速记语法来设置对象属性--以下两行代码是等价的:
{ equation }
{ equation: equation }你的第二个例子做不到同样的事情!在第二个例子中,您试图用方法调用来使用速记,这是行不通的。在示例三中,您试图构造encodeURIComponent(equation)的返回值,它也不能工作(它返回一个字符串)。
Fawaz的第一个示例几乎有效,但是行为上有一个细微的差别--因为他们已经将变量命名为test,传递给Axios的对象的关键也将是test。记住,这些是等价的:
{ 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) })发布于 2018-01-31 15:02:48
使用速记似乎有问题。就像这样:
const test = encodeURIComponent(equation); // no braces here
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)或
axios.post(`${this.state.rootUrl}/integrate`, { test: encodeURIComponent(equation) })https://stackoverflow.com/questions/48545158
复制相似问题