javascript - 在 React 中更新父级中的状态时如何更新子级中的 props?

标签 javascript reactjs

我正在开发一个包含多个组件和 API 的 React 应用程序。我有一个与 API 连接的父组件。我有一个子组件,它有一个显示 API 数据的弹出模式。我在子组件内创建了模式,并在收到 API 数据时在父组件内调用它。现在,我使用 Material UI Circular Progress 更新此内容,以避免延迟 API 响应而导致可用性降低。

我在父组件中调用 API,并最初将名为 isLoading 的状态设置为 true。在 API success 方法中,我将 isLoading 设置为 false。同时,我在子组件中打开模式,并将 isLoading 状态作为带有 API 数据的 prop 发送。在子组件中,我收到这些 Prop 。最初,我将 isLoading 设置为 True 并将状态设置为 True。然后,当父级中的 API 成功时,我等待 false,但问题是即使 API 成功后,我也无法立即从父级到子级获取更新的 isLoading (false)。但是,它正在渲染函数中更新,我可以获取projectAllData。我只是无法在 ComponentDidMount 中使用更新的 isLoading 设置状态

父级:

class Taskboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      projectAllData: undefined,
      open: false,
      isLoading: true,
    };
  }

  getPojectId = (projectId) => {
    this.setState({ open: true })

    API.get('project/' + projectId)
      .then(({ data }) => {
        this.setState({
          projectAllData: data.response,
          isLoading: false,
        });
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      })
  }

  render(){
    return(
      {
          this.state.open ?
            <ProjectModal
              handleOpen={this.state.open}
              handleClosed={this.handleClose}
              projectData={this.state.projectAllData}
              isLoading={this.state.isLoading}
            /> : null
        }
    )
  }
}

child :

class ProjectModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            single: ''
        }
    }

    componentDidMount() {
       this.setState({ single: !this.props.isLoading? this.props.projectData.currentAssigneeName : '' }) 
       //Initially this is True and is not updating when isLoading is False
    }

    render() {
      return(
         {
           this.props.isLoading ?
             <CircularProgress/>
           :
           <Modal />
         }
      )
    }
}

最佳答案

componentDidMount 仅被调用一次,即在初始渲染之后。对于您的用例,您需要 componentDidUpdate

componentDidUpdate(prevProps) {
  if (this.props.isLoading !== prevProps.isLoading) {    
    this.setState({ /* here goes you state update*/ })
  }
}

关于javascript - 在 React 中更新父级中的状态时如何更新子级中的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55914740/

相关文章:

javascript - 从数组值开始按升序追加元素

javascript - 最大化打印宽度 CSS3

java - Flux 架构和后端

javascript - 从 chrome 开发工具获取 CSS 作为 JavaScript 对象值

reactjs - 为什么 componentWillUnmount 在下一个组件 componentWillMount 之后触发?

c# - 如何在 JavaScript 方法中获取 ASP.NET DataGrid 控件的选定行索引?

javascript读取新的rss条目并创建通知

javascript - 显示 JS ToDo 列表中有多少已完成的任务 VS 有多少任务

javascript - 为什么每次渲染时都会调用 `useEffect` 处的清理函数?

reactjs - 带 React Helm 的 Razzle : Meta tags displayed wrong in crawlers when using dynamic values from Axios