【发布时间】: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