Redux:对象作为 React 子项无效(发现:[object Promise])
2020-06-11
75
我正在使用 react、redux 和 axios 制作此应用程序,其中一个组件显示完整的地址列表,下一个组件显示一个选定的地址。地址列表组件工作正常,但单个视图组件出现问题,返回以下错误:
在涉及 changeSelected->address 的 redux 链中的某个地方,发送了一个承诺而不是承诺的结果。我很难确定这一点,因为我对多地址视图 fetchAddresses-> 使用了类似的结构地址工作正常。
这是我的反应组件
const Card = async (props) => {
const { changeSelected,address } = props
console.log(address)
useEffect(() => {
changeSelected(1);
},[changeSelected(1)])
if (!address){
return <h1>No results</h1>
} else {
return (
<React.Fragment>
<CssBaseline />
<Container maxWidth="sm">
<Typography component="div" style={{ backgroundColor: '#cfe8fc', height: '100vh' }} >
<Typography variant="h6" >{address.body}</Typography>
</Typography>
</Container>
</React.Fragment>
);
}
}
Card.propTypes = {
changeSelected: PropTypes.func.isRequired,
address: PropTypes.object.isRequired,
}
const mapStateToProps = state => ({
address: state.address.address,
})
export default connect(mapStateToProps, {changeSelected})(Card)
这是我分派的动作
export const changeSelected = (postData) => dispatch => {
console.log(postData)
axios.get(`https://jsonplaceholder.typicode.com/posts/${postData}`)
.then(addresses => {
console.log(addresses)
dispatch({
type: CHANGE_SELECTED,
payload: addresses.data
})}).catch(err => {
dispatch({
//if there's an error, send the user a card saying so
type: CHANGE_SELECTED,
payload: [{id:0,nickName:'error',content:'please contact cutomer service at 010-314-1150'}]
})
console.log(err)
})
}
这是我的减速器
//create initial state
const initialState = {
addresses: [],
address:{}
}
export default (state = initialState, action) => {
switch(action.type) {
case FETCH_ADDRESSES:
return{
...state,
addresses: action.payload
}
case CHANGE_SELECTED:
return{
address: action.payload
}
default:
return state
}
}
响应正在到达减速器,但在返回承诺之前调用了错误消息。
1个回答
结果发现问题在于将我的反应组件 (Card) 指定为“异步”。去掉它之后,它就正常工作了。
thatguy1155
2020-06-11