Алексей Левчук Lesson7#64
Conversation
|
Возникла проблема/вопрос. http://localhost:8040/users - редиректит нормально, но если в конце добавляю слэш (http://localhost:8040/users/) - не работает. |
|
Ещё вопросик. |
|
И если будет время и возможность, хотелось бы получить ревью на code style в целом (что лучше, экспорировать при объявлении или в конце файла и т.п.) |
| @@ -0,0 +1,26 @@ | |||
| import { combineReducers } from 'redux' | |||
There was a problem hiding this comment.
придирка не к коду, а к именованию файлов. Люди любят создавать папку, где уточняется название компонента или функционал внутреннего файла index.js, таким образом облегчая себе запись импорта в другой файл. Но! В среде разработки (прим. visual studio code) будет сложно работать сразу с несколькими открытыми файлами index.js. На всех вкладках будет прописано 'index.js' - как я пойму, что там внутри? Только переключая вкладки и чекая код. Вот если бы название было reducer.js, мне не пришлось бы это делать)
There was a problem hiding this comment.
Да, есть такое. Я обычно навожу на файл и жду когда путь подстветится)
| users: users | ||
| } | ||
| ) | ||
| } |
There was a problem hiding this comment.
export const RECEIVE_USERS = 'RECEIVE_USERS'
export const ADD_USER = 'ADD_USER'
import axios from 'axios'
export function fetchUsers() {
return function(dispatch) {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(response => dispatch({type: RECEIVE_USERS, payload: response.data}))
}
}
// export const fetchUsers = () => dispatch => {
// return axios.get(`https://jsonplaceholder.typicode.com/users`)
// .then(response => response.data)
// .then(json => dispatch(receiveUsers(json)))
// }
export function fetchUser(user) {
return {type: ADD_USER, payload: user}
}
// export const fetchUser = () => (dispatch, getState) => {
// const users = getState()
// return dispatch(addUser(users))
// }
| return <User key={index} user={user}/> | ||
| })} | ||
| </> | ||
| ) |
There was a problem hiding this comment.
import React from 'react'
import { User } from './User'
export const UsersList = (props) => {
return <>
{props.users.map((user, index) => {
return <User key={index} user={user}/>
})}
</>
}
| } | ||
| } | ||
|
|
||
| export default connect(mapStateToProps)(Users) |
There was a problem hiding this comment.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { fetchUsers, fetchUser } from '../actions'
import { UsersList } from '../components/UsersList'
class Users extends Component {
fetchUser(user) {
this.props.dispatch(fetchUser(user));
}
componentDidMount() {
this.props.dispatch(fetchUsers())
}
render() {
return (<>
<button type="submit"
onClick={this.fetchUser.bind(this,
{username: "newUsername",
name: "newName",
email: "newEmail",
phone: "newPhone"
})}>add user</button>
<UsersList users={this.props.users} />
</>
)
}
}
const mapStateToProps = state => {
return {
users: state
}
}
export default connect(mapStateToProps)(Users)
| usersAll, | ||
| }) | ||
|
|
||
| export default rootReducer |
There was a problem hiding this comment.
import { RECEIVE_USERS, ADD_USER } from '../actions'
const reducer = (state, action) => {
switch (action.type) {
case RECEIVE_USERS:
return action.payload;
case ADD_USER:
return [...state, action.payload];
default:
return state
}
}
export default reducer;
| reducers, | ||
| applyMiddleware(...middleware) | ||
| ) | ||
|
|
There was a problem hiding this comment.
const store = createStore(
reducer,
[],
applyMiddleware(...middleware)
)
Я долго разбирался с Redux. Поэтому сделал банальную загрузку пользователей. Постараюсь к моменту проверки ДЗ сделать ещё.
Update
добавил добавление пользователя