首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >encodeURIComponent在反应中

encodeURIComponent在反应中
EN

Stack Overflow用户
提问于 2018-01-31 14:58:56
回答 2查看 11K关注 0票数 1

我有一个function函数,返回来自axios的承诺,我需要编码一个等式类型的字符串被传递给它。

代码语言:javascript
复制
const { equation } = this.state;
axios.post(`${this.state.rootUrl}/integrate`, { equation }).then(some other code)

在将字符串等式传递给API进行查询之前,我希望对其进行编码。

我试过以下几种方法,但都没有用。

代码语言:javascript
复制
axios.post(`${this.state.rootUrl}/integrate`, { encodeURIComponent(equation) })

我也试过这个:

代码语言:javascript
复制
const { equation } = this.state;
const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)

这也没用。

下面是我尝试使用的函数的完整代码:

代码语言:javascript
复制
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]});
        }
    }
  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-31 15:29:37

在最初的示例中,您使用了速记语法来设置对象属性--以下两行代码是等价的:

代码语言:javascript
复制
{ equation }
{ equation: equation }

你的第二个例子做不到同样的事情!在第二个例子中,您试图用方法调用来使用速记,这是行不通的。在示例三中,您试图构造encodeURIComponent(equation)的返回值,它也不能工作(它返回一个字符串)。

Fawaz的第一个示例几乎有效,但是行为上有一个细微的差别--因为他们已经将变量命名为test,传递给Axios的对象的关键也将是test。记住,这些是等价的:

代码语言:javascript
复制
{ test }
{ test: test }

据推测,您的API期望的是equation,而不是test,因此这是行不通的。

要获得正确的行为,您应该确保要传递的对象具有正确的键:

代码语言:javascript
复制
const test = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation: test })

// or

axios.post(`${this.state.rootUrl}/integrate`, { equation: encodeURIComponent(equation) })
票数 5
EN

Stack Overflow用户

发布于 2018-01-31 15:02:48

使用速记似乎有问题。就像这样:

代码语言:javascript
复制
const test = encodeURIComponent(equation); // no braces here
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)

代码语言:javascript
复制
axios.post(`${this.state.rootUrl}/integrate`, { test: encodeURIComponent(equation) })
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48545158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档