我有一个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: 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/