【问题标题】:Conditional Rendering in React application using tsx使用 tsx 在 React 应用程序中进行条件渲染
【发布时间】:2018-10-02 22:11:48
【问题描述】:

我正在尝试使用 Microsoft 提供的默认 React 模板根据用户在 React 应用程序中的状态向用户呈现视图。

这是我得到的错误:

picture of error

这是我的代码:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { NextButton } from './shared/NextButton'
import { StationZero } from './stations/StationZero';

interface BiodieselStudioState {
    station: string[];
    stationNumber: number;
}

export class BiodieselStudio extends 
React.Component<RouteComponentProps<{}>, BiodieselStudioState> {
    constructor() {
        super();

        this.state = {
            station: ["StationZero", "StationOne", "StationTwo",
                    "StationThree", "StationFour", "StationFive",
                    "StationSix", "StationSeven"],
            stationNumber: 0
        };
}

public render() {
    return (
        <div>
            <h1>BIODIESEL STUDIO!</h1>
            { this.chooseStation(this.state.stationNumber) }
            <NextButton />
        </div>
    );
}

chooseStation(stationNumber: number) {
    switch(stationNumber) {
        case 0: {
            return <StationZero />
            break;
        }
        case 1: {

            break;
        }
        case 2: {

            break;
        }
        case 3: {

            break;
        }
        case 4: {

            break;
        }
        case 5: {

            break;
        }
        case 6: {

            break;
        }
        case 7: {

            break;
        }
        case 8: {

            break;
        }
        default: {

        }
    }
}

我必须加载非常不同的用户界面,但这基本上是站点视图的主机,其想法是子组件将让用户完成一个活动并更新 BiodieselStudio 中的状态,这将使该应用程序根据需要运行。

很多案例陈述没有填写,但会遵循相同的模式!

非常感谢你们!

【问题讨论】:

  • BiodieselStudio.tsx 的第 36 行是什么?
  • 这是返回 的行,它可以在我的 chooseStation 函数 @FuzzyTree 的 case 0 下找到

标签: reactjs typescript frontend react-tsx


【解决方案1】:

根据错误,您的 StationZero 组件为其 props 定义了 RouteComponentProps&lt;{}&gt;

class StationZero extends React.Component<RouteComponentProps<{}>> {

但是您没有通过 RouteComponentProps 传递它,因为您没有通过 react-router 安装组件。

您可以通过从 StationZero 组件定义中删除 RouteComponentProps&lt;{}&gt; 来修复此错误:

class StationZero extends React.Component {

同时删除此break 以修复“无法访问代码”错误。

case 0: {
    return <StationZero />
    break; // not reachable because of return
}

【讨论】:

  • 这是我的问题的解决方案。谢谢!
猜你喜欢
  • 2020-01-15
  • 1970-01-01
  • 2020-09-20
  • 2021-07-18
  • 2019-09-03
  • 2019-08-18
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多