【问题标题】:How to parse local scope variable in Typescript?如何在 Typescript 中解析局部范围变量?
【发布时间】:2021-10-06 16:42:35
【问题描述】:

我正在尝试在我的 React 应用程序中将字符串解析为对象数组。

const {newsEntity} = props;
const contentInString = {newsEntity.content}; <== not working
// const contents = JSON.parse(contentInString); <== hoping to use this someday

我收到以下错误ESLint: Parsing error: ',' expected.

我试图删除花括号,但它给出了undefined

内容:

[{"content":"Umi Kalsum berharap kondisinya tetap baik","type":"text"},{"content":"Dream - Setelah menempuh perjalanan darat cukup panjang untuk menemui wanita diduga telah menghina keluarganya, Umi Kalsum dan Ayah Rozak akhirnya kembali rumahnya di Depok, Jawa Barat. Perjalanan panjang itu ternyata menguras tenaga orang tua Ayu Ting Ting tersebut.","type":"text"}

{newsEntity} 的内容我注意到只在渲染过程中可见

return (<div> {newsEntity.content}</div>  );

【问题讨论】:

  • 你能显示newsEntity.content的示例数据吗?
  • 你对newsEntity有价值吗?
  • {newsEntity.content} 是语法错误。也许你的意思是newsEntity.content
  • 看起来你必须使用地图,因为格式是数组,所以你可以渲染

标签: reactjs typescript tsx


【解决方案1】:

const contentInString = {newsEntity.content}; 这会导致语法错误。

你应该这样提取const contentInString = newsEntity?.content

【讨论】:

  • 你也在工作。显然这就是为什么你建议在渲染过程中使用? 来保证空值安全......
  • 是的,只是空检查,这样它就不会崩溃:)
【解决方案2】:

如果你想分配新的对象使用:

const contentInString = {content: newsEntity.content};

如果您想从newsEntity 获取content,请使用:

const contentInString = newsEntity.content;

关于问题的最后一部分 - 这是 TypeScript 错误,它会提示您的类型出现问题。 你可以或

  • 创建新变量并自动推断类型
  • 或者手动修复类型

【讨论】:

  • 顺便说一句,当我尝试使用 JSON 解析时,它给了我Argument of type '{ content: string; }' is not assignable to parameter of type 'string'.
  • 那是 TypeScript 抱怨不正确的类型。这就是说不允许将对象分配到字符串变量中。只需修复变量的类型或创建新的变量
【解决方案3】:
//Checkout this hopefully this will help you
let GblVar=100;  
 
function Fn() {          //function
 
  console.log(GblVar)
 
  if (true) {         //code block
    console.log(GblVar)
  }
 
  function nested() {         //nested function within someFn1
    console.log(GblVar)
  }
 
}
 
for (let c = 0; c < 3; c++){    //code block
  console.log(GblVar);
}
 
function OthrFn1() {       //another function
  console.log(GblVar)
}
 
console.log(GblVar) 

【讨论】:

    猜你喜欢
    • 2014-11-11
    • 2014-03-02
    • 2013-10-14
    • 2013-05-10
    • 2014-07-14
    • 2022-01-12
    • 2010-11-26
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多