【问题标题】:React JS NAN 'new URLSearchParams(this.props.location.search)'React JS NAN '新 URLSearchParams(this.props.location.search)'
【发布时间】:2020-11-15 13:02:54
【问题描述】:

我正在尝试使用文本格式的参数恢复 URLSearchParams(props.location.search),但我只能成功地使用数字恢复参数。
ex = {id:1, name:'Adrien', age:23} => 结果 {id:1, name:Nan, age:23}

My code : 

Home.js 

let Home = (props) => {
let state = {
id: 1,
name: 'Sfafa',
age: 34,
};

let param = [];
for (let i in state) {
param.push(encodeURIComponent(i) + '=' + encodeURIComponent(state[i]));}

let query = param.join('&');

CreatPost.js :

class CreatePost extends Component {
constructor(props) {
super(props);
this.state = {
perso: {
id: '',
age: '',
name: '',
},
};
}
getData = () => {
let params = {};
let query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
params[param[0]] = +param[1];
**console.log(params);**
}
this.setState({
perso: params,
});
};

**My problem :** 
for the console.log(params) => 
id: 1
**name: NaN** (how can i recuperate the text-format ? ) 
age: 34

Thank you !

【问题讨论】:

    标签: reactjs nan urlsearchparams


    【解决方案1】:

    您通过+param[1] 将所有值转换为数字。 你可以稍后再做,比如:

    params[param[0]] = param[1]; // no "+", all values are strings
    this.setState({
      perso: {
        id: Number(params.id),
        name: params.name,
      },
    });
    

    或者,如果您希望使用通用方法来解析您的参数,您可以执行以下操作:

    const [key, value] = param;
    const parsedValue = Number(value);
    params[key] = isNaN(parsedValue) ? value : parsedValue;
    

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2022-01-25
      • 2022-11-23
      • 2022-07-01
      • 2021-07-12
      • 2020-01-31
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多