这是我第一次在这里发帖,所以我很乐意接受对我发帖方式和帖子本身的评论。我学习编程才 8 周,所以可能有很多错误。
在这种情况下,我特别需要以下代码方面的帮助。
// import React, { Component } from 'react'
import React from 'react'
import { connect } from 'react-redux'
// import { Link } from 'react-router-dom'
import { getUnits } from '../reducers/units'
import { Menu, Container, Grid, Header,m} from 'semantic-ui-react'
class AllUnits extends React.Component {
componentDidMount() {
console.log ("component did mount!")
debugger
this.props.dispatch(getUnits())
debugger
}
units = () => {
debugger
return this.props.units.map( unit => {
<Grid textAlign='center' columns={1}>
<Grid.Row>
<Grid.Column>
<Menu fluid vertical>
<Menu.Item className='header'>{this.position} {unit.name}</Menu.Item>
</Menu>
</Grid.Column>
</Grid.Row>
</Grid>
})
}
render() {
debugger
return (
<Container>
<Header as="h3" textAlign="center">Units</Header>
{ this.units() }
</Container>
)
}
}
const mapStateToProps = (state) => {
return { units: state.units }
debugger
}
export default connect(mapStateToProps)(AllUnits);
它以某种方式命中了调试器,但没有记录任何内容。我知道它正在访问我的路由和我的组件,因为它稍后会在某些代码中发现错误,但它永远不会 console.logs 我的消息。
提前致谢。
编辑:根据要求,我已经放入了整个组件。
Edit2:我不知道这是否相关,但是当它通过该组件中的所有调试器和 reducer 中的一两个调试器时,这是错误:
TypeError: Cannot read property 'id' of undefined
AllUnits.componentDidMount
src/components/AllUnits.js:13
10 | componentDidMount() {
11 | console.log ("component did mount!")
12 | debugger
> 13 | this.props.dispatch(getUnits())
14 | debugger
15 | }
16 |
这里是 reducer :
import axios from 'axios';
import { setFlash } from './flash';
import { setHeaders } from './headers';
import { dispatch } from 'react';
const GET_UNITS = 'GET_UNITS';
export const getUnits = (courseId) => {
return() => {
axios.get(`/api/courses/${courseId}/units`)
.then( res => {
debugger
dispatch({ type: GET_UNITS, units: res.data, headers: res.headers })
dispatch(setHeaders(res.headers))
})
.catch( err => {
dispatch(setHeaders(err.headers));
dispatch(setFlash('Failed To Retrieve Units', 'red'));
});
}
}
export default (state = [], action) => {
switch (action.type) {
case GET_UNITS:
return action.units;
default:
return state;
}
};
编辑 3:它现在正在做一些小改动。
改变 1:
const mapStateToProps = (state) => {
return { units: state.units, course: state.course }
}
变化 2:
componentDidUpdate(prevProps) {
const { dispatch, course } = this.props
if (prevProps.course.id !== course.id)
dispatch(getUnits(course.id))
}
显然,当它安装时,它没有所需的 Prop ,这也是类(class)未定义的部分原因。它在抓取类(class)之前呈现。
最佳答案
您在 componentDidMount
中调度的 getUnits
操作需要 courseId
参数,但您没有传递任何参数。
TypeError: Cannot read property 'id' of undefined
componentDidMount() {
console.log ("component did mount!")
debugger
// missing param, any props we can use here?
this.props.dispatch(getUnits(/* missing courseId param */))
debugger
}
// Action that expects courseId param
export const getUnits = (courseId) => { ... }
关于javascript - componentDidMount() 不工作但命中调试器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51109873/