首页 > 解决方案 > 如何使用在渲染 React/Redux 中定义的变量作为回报?

问题描述

如何使用变量 sexname 作为回报?有错误“sexname未定义”,如何解决?

render()
  {
    const { loading,popupVisible,edit } = this.state;
    const{information, about, data, photo,}=this.props;

    if(information.sex === 'w'){
      let sexname = 'женский'

    }else if(information.sex === 'm'){
      let sexname = 'мужской'

    }else {
      let sexname ='Пока не указано';

    }
return (
            <Aboutinfo>{

                information.sex !== null && information.sex !== undefined ?
                  sexname
                  : 'Пока не указано'

              }</Aboutinfo>
);
  }

标签: reactjsredux

解决方案


let是阻塞范围的,因此它仅在直接块中可用(块是介于 之间的任何内容{ .... },在您的情况下是在if语句中,我们可以通过将 移动let sexname到函数顶部来解决这个问题。

 render()
  {
    const { loading,popupVisible,edit } = this.state;
    const{information, about, data, photo,}=this.props;
    let sexname = ""

    if(information.sex === 'w'){
      sexname = 'женский'

    }else if(information.sex === 'm'){
      sexname = 'мужской'

    }else {
      sexname ='Пока не указано';

    }

推荐阅读