【问题标题】:how can I update a state in react using axios.get method?如何使用 axios.get 方法更新反应状态?
【发布时间】:2021-03-05 21:04:48
【问题描述】:

我有一个布局,其中有一个导航栏作为单独的组件和页面的其余部分,我的问题是当我更改导航栏中的显示类时,我希望页面更改其状态以显示每个的相关信息类,我从导航栏获取所有需要的信息,所以问题不存在,我认为问题出在 Class.js 文件中,关于如何更新状态,请帮助任何人,这是 Class.js 文件:

class Class extends React.Component {
    
    static contextType = userContext
    
    state = {
        Curriculum: [],
        Classworks: [], 
        Homeworks: []
    }

    componentDidMount() {
        console.log(this.props.location.state)
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )                      
      }
      componentDidUpdate(){
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )  
      }
    render()
        {       
            console.log(this.state.Curriculum);       
            return(
            <div className="back">
            <Navbar/>
            
            <main className= "MainContent">
                <div className="Class">
                    <h2 className="class">
                        {this.props.location.state.Name}
                    </h2>
                </div>
                <Tabs  className="Tabs" defaultActiveKey="1" centered>
                    <TabPane tab="Curriculum"  key="1">
                        <List
                        itemLayout="horizontal"
                        dataSource={this.state.Curriculum}
                        renderItem={item => (
                            <List.Item>
                                <Table striped bordered hover size="sm" >
                                    <tr>
                                        <th>
                                            #
                                        </th>
                                        <th>
                                            Title
                                        </th>
                                    </tr>
                                    <tr>
                                        <td>
                                            
                                        </td>
                                        <td>
                                            {item.Title}
                                        </td>
                                    </tr>
                                </Table>
                            </List.Item>
                        )}
                        />
                    </TabPane>
                    <TabPane tab="ClassWorks"  key="2">
                    
                    </TabPane>
                    <TabPane tab="HomeWorks" key="3">
                        
                    </TabPane>
                    <TabPane tab="Videos" key="4">
                    
                    </TabPane>
                    <TabPane tab="Sessions" key="5">
                    
                    </TabPane>
                    <TabPane tab="quizzes" key="6">
                    
                    </TabPane>
                    <TabPane tab="Exams" key="7">
                    
                    </TabPane>
                </Tabs>
            </main>
            <br/>
            <footer className="Footer">Designed by Eng. Omar Redwan</footer>
        </div>
        )}
}

【问题讨论】:

  • 此时有什么问题?我看到您已经在使用检索到的数据设置状态。
  • 这是正确的,但是当我尝试使用导航栏显示另一个类时,它不会改变状态,它只需要最初分配的状态,并且导航栏会正确发送相关信息,但是Class.js 不使用它来更改其状态并从 api 获取与该类相关的信息
  • 你的意思是在 TabPane 中?显示阶级变化的部分在哪里?您更改父组件中的类?
  • 这一切都是在路由器中渲染的吗? ClassNumber 是从Navbar 中的链接发送的some 路由状态的一部分吗?问题是什么?您是否尝试切换TabPane tab="Curriculum" 选项卡?我没有看到状态更新的问题,所以有点不清楚你认为问题是什么。
  • 是的,我正在使用路由器,链接发送 ClassNumber,Name,它发送它们没有问题,我使用 consol.log 检查信息,但它没有从api一旦props.location发生变化,一旦文件从导航栏收到的props.location发生变化,我怎样才能让它使用axios获取信息??

标签: reactjs react-component react-state react-state-management


【解决方案1】:

我认为您的问题在于更新状态对吗?然后 您必须将 prevProps 和 prevState 作为参数传递给 componentDidUpdate。要跟踪 props 的变化,您必须仅在 props 发生变化时获取 prevProps 和 componentDidUpdate 调用。这意味着当位置道具发生变化时,它将更新您需要执行的状态。

class Class extends React.Component {
    
    static contextType = userContext
    
    state = {
        Curriculum: [],
        Classworks: [], 
        Homeworks: []
    }

    componentDidMount() {
        console.log(this.props.location.state)
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )                      
      }
      componentDidUpdate(prevProps,prevState){
if(prevProps.location.state.classNumber!==this.props.location.state.classNumber){
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )
}  
      }
    render()
        {       
            console.log(this.state.Curriculum);       
            return(
            <div className="back">
            <Navbar/>
            
            <main className= "MainContent">
                <div className="Class">
                    <h2 className="class">
                        {this.props.location.state.Name}
                    </h2>
                </div>
                <Tabs  className="Tabs" defaultActiveKey="1" centered>
                    <TabPane tab="Curriculum"  key="1">
                        <List
                        itemLayout="horizontal"
                        dataSource={this.state.Curriculum}
                        renderItem={item => (
                            <List.Item>
                                <Table striped bordered hover size="sm" >
                                    <tr>
                                        <th>
                                            #
                                        </th>
                                        <th>
                                            Title
                                        </th>
                                    </tr>
                                    <tr>
                                        <td>
                                            
                                        </td>
                                        <td>
                                            {item.Title}
                                        </td>
                                    </tr>
                                </Table>
                            </List.Item>
                        )}
                        />
                    </TabPane>
                    <TabPane tab="ClassWorks"  key="2">
                    
                    </TabPane>
                    <TabPane tab="HomeWorks" key="3">
                        
                    </TabPane>
                    <TabPane tab="Videos" key="4">
                    
                    </TabPane>
                    <TabPane tab="Sessions" key="5">
                    
                    </TabPane>
                    <TabPane tab="quizzes" key="6">
                    
                    </TabPane>
                    <TabPane tab="Exams" key="7">
                    
                    </TabPane>
                </Tabs>
            </main>
            <br/>
            <footer className="Footer">Designed by Eng. Omar Redwan</footer>
        </div>
        )}
}

【讨论】:

  • componentDidUpdate 会触发,无论您是否检查以前的道具,但如果这解决了问题,那就值得了。
  • 但是这种情况会阻止总是更新
  • 使用 useEffect hooks 很简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2019-10-15
  • 2020-01-12
  • 1970-01-01
相关资源
最近更新 更多