Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Алексей Левчук Lesson7 #64

Open
wants to merge 40 commits into
base: master
Choose a base branch
from

Conversation

Headmaster11
Copy link
Contributor

@Headmaster11 Headmaster11 commented Feb 11, 2019

Я долго разбирался с Redux. Поэтому сделал банальную загрузку пользователей. Постараюсь к моменту проверки ДЗ сделать ещё.
Update
добавил добавление пользователя

@Headmaster11
Copy link
Contributor Author

Headmaster11 commented Feb 12, 2019

Возникла проблема/вопрос. http://localhost:8040/users - редиректит нормально, но если в конце добавляю слэш (http://localhost:8040/users/) - не работает.
Как от этого избавиться (чтобы редирект шёл на PageNotFound)? Я вычитал в доке https://reacttraining.com/react-router/web/api/Route/strict-bool, но всё равно редиректит на пустую страницу

@Headmaster11
Copy link
Contributor Author

Ещё вопросик.
Допускается ли в реакт в рамках проекта использовать class components и function components? Или это дурной тон, и надо использовать один стиль?

@Headmaster11
Copy link
Contributor Author

И если будет время и возможность, хотелось бы получить ревью на code style в целом (что лучше, экспорировать при объявлении или в конце файла и т.п.)

@@ -0,0 +1,26 @@
import { combineReducers } from 'redux'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

придирка не к коду, а к именованию файлов. Люди любят создавать папку, где уточняется название компонента или функционал внутреннего файла index.js, таким образом облегчая себе запись импорта в другой файл. Но! В среде разработки (прим. visual studio code) будет сложно работать сразу с несколькими открытыми файлами index.js. На всех вкладках будет прописано 'index.js' - как я пойму, что там внутри? Только переключая вкладки и чекая код. Вот если бы название было reducer.js, мне не пришлось бы это делать)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, есть такое. Я обычно навожу на файл и жду когда путь подстветится)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже вариант))))

users: users
}
)
}
Copy link
Owner

@LeonEsquire LeonEsquire Feb 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}/>
})}
</>
)
Copy link
Owner

@LeonEsquire LeonEsquire Feb 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Copy link
Owner

@LeonEsquire LeonEsquire Feb 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Copy link
Owner

@LeonEsquire LeonEsquire Feb 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
)

Copy link
Owner

@LeonEsquire LeonEsquire Feb 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const store = createStore(
  reducer, 
  [],
  applyMiddleware(...middleware)
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants