Skip to content

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

Open
Headmaster11 wants to merge 40 commits into
LeonEsquire:masterfrom
Headmaster11:lesson7_2
Open

Алексей Левчук Lesson7#64
Headmaster11 wants to merge 40 commits into
LeonEsquire:masterfrom
Headmaster11:lesson7_2

Conversation

@Headmaster11

@Headmaster11 Headmaster11 commented Feb 11, 2019

Copy link
Copy Markdown
Contributor

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

@Headmaster11

Headmaster11 commented Feb 12, 2019

Copy link
Copy Markdown
Contributor Author

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

@Headmaster11

Copy link
Copy Markdown
Contributor Author

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

@Headmaster11

Copy link
Copy Markdown
Contributor Author

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

Comment thread AliakseiLiauchuk/src/index.js Outdated
Comment thread AliakseiLiauchuk/src/index.js Outdated
@@ -0,0 +1,26 @@
import { combineReducers } from 'redux'

Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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

users: users
}
)
}

@LeonEsquire LeonEsquire Feb 13, 2019

Copy link
Copy Markdown
Owner

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

@LeonEsquire LeonEsquire Feb 13, 2019

Copy link
Copy Markdown
Owner

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)

@LeonEsquire LeonEsquire Feb 13, 2019

Copy link
Copy Markdown
Owner

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

@LeonEsquire LeonEsquire Feb 13, 2019

Copy link
Copy Markdown
Owner

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

@LeonEsquire LeonEsquire Feb 13, 2019

Copy link
Copy Markdown
Owner

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.

2 participants