【发布时间】:2018-05-23 18:18:04
【问题描述】:
我尝试映射获取的数据,但我的映射总是出错,因为在我使用 map 函数之前尚未获取数据。我可以使用点击事件从获取的数据中获取特定元素。
我获取数据的父类,我需要啤酒数据进行映射。
class App extends Component{
constructor(props){
super(props);
this.props.fetchUser();
this.props.fetchBeers();
}
我尝试映射啤酒的课程:
class BeersLanding extends Component{
getBeers = () => {
let beers= this.props.beers;
console.log(beers);
console.log(beers[0]);
console.log(beers[1]);
}
constructor(props){
super(props);
}
render(){
const {loading} =this.props;
console.log(this.props.beers)
return(
<div style={{textAlign:'center'}}>
...
<input type="text" placeholder="Search.." name="search"></input>
<button type="submit" onClick={() =>this.getBeers()} >Submit</button>
<div className={'beersContainer'}>
{this.props.beers.map((beer,index) =>(
<div className={'card'}>
hello
</div>
))}
</div>
</div>
);
}
}
动作方法:
export const fetchBeers = () => async dispatch => {
const res = await axios.get('/api/beers');
dispatch({type:FETCH_BEERS, payload:res.data});
};
减速器:
export default function(state=null, action){
// console.log(action);
switch(action.type){
case FETCH_BEERS:
return action.payload;
default:
return state;
}
}
【问题讨论】:
-
您收到有关选择标签的错误
-
不要在构造函数中触发获取,使用
componentDidMount。此外,无论您是否正在加载,您都需要保持状态。然后是在渲染“啤酒”之前简单检查布尔值的问题。
标签: reactjs redux axios redux-thunk