我已经构建了一个从api搜索用户的应用程序。我使用react和redux。单击使用空输入搜索或搜索相同字符串时,问题就开始了。下面是您需要的所有数据。我恐怕自己无法解决这个问题。
我的 reducer :
import {FETCH_USERS} from '../actions/index';
export default function(state = [], action) {
switch (action.type){
case FETCH_USERS:
return {...state, users: action.payload.data.items
}
}
return state;
}
我的操作与reducer相关:
import axios from 'axios';
const root_url = `https://api.github.com/search/users`;
export const FETCH_USERS = 'FETCH_USERS';
export function fetchUsers(login) {
const request = axios.get(`${root_url}?q=${login}`);
// const andSoOn = request.data;
return {
type: FETCH_USERS,
payload: request
}
}
和容器:
import React,{Component} from 'react';
import {connect} from 'react-redux';
import _ from 'lodash';
import Details from '../../components/Details/Details';
import classes from './UserList.css';
class UserList extends Component {
state = {
show: {}
}
showContentFunction(index) {
const itemToShow = {
...this.state.show,
[index]: true
};
this.setState({show: itemToShow})
}
render(){
return (
_.map(this.props.users, user=> user.slice(0,10).map((e,index) => (
<div
className={classes.Items}
key={e.id}
onClick={() => this.showContentFunction(e.id)}
>
{ !this.state.show[e.id] ? e.login : null}
{ this.state.show[e.id] ? <Details
className={classes.Details}
name={e.login}
image={e.avatar_url}
score={e.score}
link={e.html_url}
/> : null}
</div>
)
)
)
)
}
}
function mapStateToProps(state) {
return {
users: state.users
}
}
export default connect(mapStateToProps)(UserList);
单击按钮时没有字符串或secon时间与相同字符串的错误: 未处理的拒绝(TypeError):无法读取未定义的属性“项目”
答案 0 :(得分:1)
在我的操作中,你应该使用redux-thunk进行异步操作。
export function fetchUsers(login) {
// const andSoOn = request.data;
return (dispatch, getState) => {
const request = axios.get(`${root_url}?q=${login}`);
//You make request here
//when received data from server then return data with type of action
return {
type: FETCH_USERS,
payload: data
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
在Reducer中,您应声明初始状态
initState = {
users: []
}