【问题标题】:Why is render() throwing this error: ':' expected为什么 render() 会抛出此错误:':' 预期
【发布时间】:2018-12-14 13:45:57
【问题描述】:

错误':' expected 出现在渲染方法中并指向&&this.state.obj 的类型为 MyType

type MyType = {
    name: string,
};

constructor(props) {
   super(props);
   this.state = {
       obj: null
   };
}

componentDidMount() {
    this.setState({obj: {name: 'Vasya'}});
}

render() {
    return {this.state.obj && <MyComponent />};
}

【问题讨论】:

  • 你不在 JSX 里面,{ 没有开始插值; return { 正在启动一个对象

标签: reactjs jsx


【解决方案1】:

您错误地实现了 return 语句 - 使用括号 return () 而不是花括号。使用return {},您将返回一个对象。 另外,请注意,最好在渲染之前从状态中解构数据。

render() {
    const {obj} = this.state;
    return (obj && <MyComponent />);
}

【讨论】:

  • 为什么在渲染之前从状态中解构数据更好?只是好奇!
  • 有几个原因。当您在渲染方法中有多个变量或任何时候,它更具可读性。例如。 const {foo, bar, user, data} = this.state。没有这个,你总是要输入this.state.user this.state.data 非常重复,你不想重复不必要的代码。
  • 希望对您有所帮助@Smarticles101
【解决方案2】:

return 正在返回一个对象,而不是 jsx。试试这个

type MyType = {
    name: string,
};

constructor(props) {
   super(props);
   this.state = {
       obj: null
   };
}

componentDidMount() {
    this.setState({obj: {name: 'Vasya'}});
}

render() {
    return (
        {this.state.obj && <MyComponent />}
    );
}

或者这个:

type MyType = {
    name: string,
};

constructor(props) {
   super(props);
   this.state = {
       obj: null
   };
}

componentDidMount() {
    this.setState({obj: {name: 'Vasya'}});
}

render() {
    if (this.state.obj)
        return <MyComponent />;
    else
        return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2018-05-16
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2015-11-27
    • 2015-10-11
    • 1970-01-01
    相关资源
    最近更新 更多