我有一个组件SinglePost
,当在主页中以及通过路径Post
单击另一个组件/post/:id
时,该组件将被调用。问题是,在SinglePost
中,我通过componentDidMount
上的Redux调用了API,然后在componentWillReceiveProps
上要求它。而且,当您从URL /post/:id
访问该组件时,道具在加载后会抛出未定义的两次。
我正在关注React / Redux教程,以使用API调用制作CRUD网络应用。并且,在该项目中,道具在两种情况下都可以正常加载(通过主页导航和URL)。我做了完全一样的事情,但是没有用。这是一个问题,还是这样工作?
这是SinglePost
组件:
import { connect } from 'react-redux';
import { mostrarPublicacion } from '../../actions/publicacionesActions';
state = {
publicacion: {},
}
componentDidMount() {
const {id} = this.props.match.params;
//this is the action defined on PublicacionesActions
this.props.mostrarPublicacion(id);
}
componentWillReceiveProps(nextProps, nextState) {
const {publicacion} = nextProps;
this.setState({
publicacion
})
}
const mapStateToProps = state => ({
publicacion: state.publicaciones.publicacion
})
export default connect(mapStateToProps, {mostrarPublicacion}) (SinglePost);
Publicaciones操作:
export const mostrarPublicacion = (id) => async dispatch => {
const respuesta = await axios.get(`http://www.someapi.com:8000/api/publicacion/${id}`);
dispatch({
type: MOSTRAR_PUBLICACION,
payload: respuesta.data
})
}
我调试了它,它实际上返回了出版物。实际上,它可以在SinglePost组件中正确呈现。但是首先,当通过url访问组件时,它会加载未定义的内容。
RootReducer:
import { combineReducers } from 'redux';
import publicacionesReducer from './publicacionesReducer';
import seccionesReducer from './seccionesReducer';
export default combineReducers({
publicaciones: publicacionesReducer,
secciones: seccionesReducer
});
PublicacionesReducer:
export default function (state = initialState, action) {
switch(action.type) {
case MOSTRAR_PUBLICACION:
return {
...state,
publicacion: action.payload
}
default:
return state
}
}
这是Router
组件(包装为<Provider store={store}>
):
<Switch>
<Route exact path='/post/:id' component={SinglePost} />
</Switch>
我实际上要求(!this.state.publication)
并返回null,以渲染组件。它正在工作,但这是必需的吗?