实际上,我想要做的如下:
我正在使用github API,我想在“用户”组件中显示搜索结果列表
搜索后,结果在redux的用户状态下出现,但只显示一个空的div
我不知道我在做什么错吗?
我还为此项目创建了一个沙盒: https://sh48l.csb.app/
动作文件
import {SEARCH_USERS} from './types';
import axios from 'axios';
export const searchUsers = text => async dispatch => {
const response = await axios.get(
`https://api.github.com/search/users?q=${text}&client_id=${process.env
.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env
.REACT_APP_GITHUB_CLIENT_SECRET}`
);
dispatch({
type: SEARCH_USERS,
payload: response.data.items
});
};
Reducer文件
import {SEARCH_USERS} from '../actions/types';
const initialState = [];
export default function(state = initialState, action) {
switch (action.type) {
case SEARCH_USERS:
return [...state, action.payload];
default:
return state;
}
}
存储文件
import {createStore, applyMiddleware} from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
combineReducer文件
import {combineReducers} from 'redux';
import usersReducer from './users';
import alertReducer from './alert';
export default combineReducers({
users: usersReducer,
alert: alertReducer
});
用户组件
import React from 'react';
import UserItem from './UserItem';
import {connect} from 'react-redux';
const Users = ({users}) => {
return (
<div style={singleUserStyle}>
{users.map(user => <UserItem key={user.id} user={user} />)}
</div>
);
};
const singleUserStyle = {
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gridGap: '1rem'
};
const mapStateToProps = state => ({
users: state.users
});
export default connect(mapStateToProps)(Users);
UserItem组件
import React from 'react';
const UserItem = user => {
const {login, avatar_url} = user;
return (
<div className="card text-center">
<img
src={avatar_url}
alt=""
className="rounded"
style={{width: '60px'}}
/>
<h3>
{login}
</h3>
</div>
);
};
export default UserItem;