【问题标题】:React render function not updating反应渲染功能不更新
【发布时间】:2019-05-21 03:58:55
【问题描述】:

我有以下代码 - 我想更改单击按钮时呈现的反应组件。但是,单击该按钮什么也不做。这是父类:

export default class SupportsContent extends React.Component {
  currentPage = "userSupportsList";
  goToPage = page => {
    this.currentPage = page;
  }
render() {
    let content = "";
    if (this.currentPage === "userSupportsList") {
      content = <UserSupportsList goToPage={this.goToPage} />
    } else if (this.currentPage === "chooseNewSupport") {
      content = <ChooseNewSupport goToPage={this.goToPage} />
    } else if (this.currentPage === "editSupport") {
      content = <EditSupport goToPage={this.goToPage} />
    } 
    return (
      <Grid>
        {content}
      </Grid>
    );
  }
}

我有以下子组件定义:

function UserSupportsList(props) {
  return (
    <ListItem button onClick={function () {props.goToPage("chooseNewSupport");}}></ListItem> 
  );
}
function ChooseNewSupport(props) {
  return (
    <p>Choose New Support</p>
    );
}

function EditSupport(props) {
  return (
    <p>Edit Support</p>
    );
}

【问题讨论】:

  • goToPage() 需要手动绑定到.this 我相信
  • 阅读how to use state。你不能只设置变量。

标签: javascript reactjs onclick react-props react-component


【解决方案1】:

React 根据两个条件更新组件:如果组件的 props 发生变化,或者使用 this.setState 函数更新状态。

我建议您编辑组件以使用状态而不是变量:

class SupportsContent extends Component {
    state = {
        currentPage: "userSupportsList"
    }

    goToPage = page => this.setState({ currentPage: page })

    render() {
        let content = "";
        if (this.state.currentPage === "userSupportsList") {
            content = <UserSupportsList goToPage={this.goToPage} />
        } else if (this.state.currentPage === "chooseNewSupport") {
            content = <ChooseNewSupport goToPage={this.goToPage} />
        } else if (this.state.currentPage === "editSupport") {
            content = <EditSupport goToPage={this.goToPage} />
        } 
        return (
            <Grid>
                {content}
            </Grid>
        );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 2020-05-04
    • 2021-05-25
    • 2021-10-23
    • 1970-01-01
    • 2018-07-17
    • 2017-01-23
    • 2020-09-17
    相关资源
    最近更新 更多