gpt4 book ai didi

javascript - 通过reducer获取相同数据或空数据

转载 作者:行者123 更新时间:2023-12-03 01:48:34 25 4
gpt4 key购买 nike

我已经构建了一个用于从 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);

当我单击没有字符串的按钮或第二次使用相同字符串的按钮时出现错误:未处理的拒绝(TypeError):无法读取未定义的属性“items”

最佳答案

在我的操作中,您应该使用 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中,你应该声明init状态

initState = {
users: []
}

关于javascript - 通过reducer获取相同数据或空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com