Reactjs 如何正确要求组件上的道具
我有一个组件Reactjs 如何正确要求组件上的道具,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我有一个组件SinglePost,当在主页中单击另一个组件Post时,也可以通过路径/Post/:id调用该组件。问题是,在SinglePost中,我通过Redux在componentDidMount上调用一个API,然后在componentWillReceiveProps上请求它。当您从URL/post/:id访问组件时,道具在加载后会抛出两次undefined 我在学习React/Redux教程,制作一个带有API调用的CRUD web应用程序。而且,在该项目中,在这两种情况下(通过主页导航
SinglePost
,当在主页中单击另一个组件Post
时,也可以通过路径/Post/:id
调用该组件。问题是,在SinglePost
中,我通过Redux在componentDidMount
上调用一个API,然后在componentWillReceiveProps
上请求它。当您从URL/post/:id
访问组件时,道具在加载后会抛出两次undefined
我在学习React/Redux教程,制作一个带有API调用的CRUD web应用程序。而且,在该项目中,在这两种情况下(通过主页导航和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);
公共事务:
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访问组件时,它会加载未定义的内容
减根剂:
import { combineReducers } from 'redux';
import publicacionesReducer from './publicacionesReducer';
import seccionesReducer from './seccionesReducer';
export default combineReducers({
publicaciones: publicacionesReducer,
secciones: seccionesReducer
});
公共收入减少者:
export default function (state = initialState, action) {
switch(action.type) {
case MOSTRAR_PUBLICACION:
return {
...state,
publicacion: action.payload
}
default:
return state
}
}
这是路由器
组件(包装在
中):
实际上,我要求
(!this.state.publication)
并返回null,以呈现组件。它正在发挥作用,但它是必要的?首先,你认为公共宣传的真正来源是什么?其次,请看。@jornsharpe它来自一个设置在PublicacionReducer上的状态,在调用PublicacionAction上的API后,请给出一个,我们看不到任何一个。你做过调试吗?有人提出要求吗?在存储中设置正确的值?“正确的道具通过了吗?”琼尔夏普说。是的,请求被提出了。而且效果很好。只是当通过'/post/:id'加载页面时,发布首先加载未定义的内容。我必须在render的方法上要求它,为什么不呢?在安装组件之前,您不会启动请求。而且你还没有展示它是如何联系在一起的。首先,你认为publicacion实际上来自哪里?其次,请看。@jornsharpe它来自一个设置在PublicacionReducer上的状态,在调用PublicacionAction上的API后,请给出一个,我们看不到任何一个。你做过调试吗?有人提出要求吗?在存储中设置正确的值?“正确的道具通过了吗?”琼尔夏普说。是的,请求被提出了。而且效果很好。只是当通过'/post/:id'加载页面时,发布首先加载未定义的内容。我必须在render的方法上要求它,为什么不呢?在安装组件之前,您不会启动请求。而且你还没有展示它是如何连接的。
<Switch>
<Route exact path='/post/:id' component={SinglePost} />
</Switch>