Reactjs 为什么render()抛出此错误:';:';预期

Reactjs 为什么render()抛出此错误:';:';预期,reactjs,jsx,Reactjs,Jsx,错误:“预期的出现在渲染方法中,并指向&&this.state.obj具有类型MyType type MyType = { name: string, }; constructor(props) { super(props); this.state = { obj: null }; } componentDidMount() { this.setState({obj: {name: 'Vasya'}}); } render() { r

错误
:“预期的
出现在渲染方法中,并指向
&&
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 />};
}
类型MyType={
名称:string,
};
建造师(道具){
超级(道具);
此.state={
obj:null
};
}
componentDidMount(){
this.setState({obj:{name:'Vasya'}});
}
render(){
返回{this.state.obj&&};
}

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 />}
    );
}
类型MyType={
名称:string,
};
建造师(道具){
超级(道具);
此.state={
obj:null
};
}
componentDidMount(){
this.setState({obj:{name:'Vasya'}});
}
render(){
返回(
{this.state.obj&&}
);
}
或者这个:

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;
}
类型MyType={
名称:string,
};
建造师(道具){
超级(道具);
此.state={
obj:null
};
}
componentDidMount(){
this.setState({obj:{name:'Vasya'}});
}
render(){
if(this.state.obj)
回来
其他的
返回null;
}

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

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

您不在JSX中,
{
没有开始插值;
return{
正在启动一个对象。为什么在呈现之前从状态中解构数据更好?只是好奇!有几个原因。当呈现方法中有多个变量时,或者在任何时候。例如
常量{foo,bar,user,data}=this.state
。如果没有这个,您将始终必须键入
this.state.user
this.state.data
这是非常重复的,您不想重复不必要的代码。希望这对您@Smarticles101有所帮助