const options = [
{
value: 'wifi',
title: 'WiFi',
},
{
value: 'isBT',
title: 'BT',
},
];
class Expample extends Component {
state = {
switch = '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
return (
<Wrapper>
<SwitchGroup
onChange={this.handleChange}
name="switch"
value={this.state.switch}
options={options}
/>
</Wrapper>
);
}
}
class SwitchGroup extends Component {
...
handleClick(value) {
const { name, onChange } = this.props;
...
onChange({
e: {
target {
name,
value,
},
}
});
}
render() {
return(
<Wrapper>
{this.props.options.map((el, i) => (
<Switch
key={i}
onClick={() => handleClick(el.value)}
isActive={el.value === this.props.value}
...
>
{el.title}
</Switch>
))}
<Wrapper />
);
}
}
componentWillReceiveProps({ isOpen, article, loadArticleComments }) {
loadArticleComments(article.id)
}
componentWillReceiveProps({ isOpen, article, loadArticleComments }) {
if (
!article.commentsLoaded &&
!article.commentsLoading &&
!this.props.isOpen &&
isOpen
) {
loadArticleComments(article.id)
}
}
case "LOAD_ARTICLE_COMMENTS_SUCCESS": {
return articleState
.setIn(["entities", action.payload.articleId, "commentsLoading"], false)
.setIn(["entities", action.payload.articleId, "commentsLoaded"], true);
}
return (
<div>
<h5>{comment.user}</h5>
{comment.text}
</div>
);
import { login } from './loginDucks';
class UserForm extends Component {
...
handleSubmit = e => {
this.props.login(this.state.form);
}
...
render() {
const { isLoading, isError, shouldRedirect } = this.props;
if (shouldRedirect) <Redirect to="/index" >;
return (
...
);
}
}
const mapStateToProps = state => ({
isLoading: state.login.isLoading,
isError: state.login.isError,
shouldRedirect: state.login.shouldRedirect,
});
const mapDispatchToProps = {
login,
};
export default connect(mapStateToProps, mapDispatchToProps)(UserForm);
const LOGIN_REQUEST = 'LOGIN_REQUEST';
const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_ERROR = 'LOGIN_ERROR';
const loginSuccess = data => ({
type: LOGIN_SUCCESS,
payload: data,
});
const loginError = data => ({
type: LOGIN_ERROR,
});
export const login = form => async dispatch => {
try {
const res = await axios.post('/api/user', form);
if (!res.data) dispatch(loginError());
dispatch(loginSuccess());
} catch e {
dspatch(loginError());
}
}
const initialState = {
isLoading: false,
isError: false,
shouldRedirect: false,
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch(type) {
case LOGIN_REQUEST:
return {
...state,
isLoading: true,
isError: false,
};
case LOGIN_SUCCESS:
return {
...state,
isLoading: false,
shouldRedirect: false,
};
case LOGIN_ERROR:
return {
...state,
isLoading: false,
isError: true,
};
default:
return state;
}
};
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Route, Switch } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import Auth from './component/AuthForm';
import Helmet from './aplication';
import loginReducer from './loginDucks';
function user(state = {}, action){
if(action.type === 'ADD_USER'){
return [
...state,
action.user
];
}
return state;
}
const rootReducer = combineReducers({
login: loginReducer,
user,
});
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancers(
applyMiddleware(thunk),
));
ReactDOM.render(
<div>
...
</div>,
document.getElementById('content')
export const getReq = data => (
async dispatch => {
try {
dispatch({
type: types.GET_REQUEST,
});
let res = await api.getReq(data);
dispatch({
type: types.GET_SUCCESS,
payload: res,
});
res = await api.getReq2(data);
} catch (error) {
dispatch({
type: types.GET_ERROR,
});
}
}
);
export const getReq = data => (
async dispatch => {
try {
dispatch({
type: types.GET_REQUEST,
});
const res = await api.getReq(data);
dispatch({
type: types.GET_SUCCESS,
payload: res,
});
dispatch(req2(res));
} catch (error) {
dispatch({
type: types.GET_ERROR,
});
}
}
);
const { date: TodayDate, transactions } = this.state;
const TodayDate = this.state.date;
const transactions = this.state.transactions;
class Example extends React.Component {
handleClick = e => {
alert(`
target: ${e.target.tagName}
currentTarget: ${e.currentTarget.tagName}
`);
};
render() {
return <button onClick={this.handleClick}><p>click me</p></button>;
}
}
function withLog(WrappedComponent) {
return class extends React.Component {
displayName = WrappedComponent.displayName || WrappedComponent.name;
componentDidMount() {
console.log(`[${this.displayName}]: componentDidMount`);
}
...
render() {
console.log(`[${this.displayName}]: render`);
return <WrappedComponent {...this.props} />;
}
}
}
class MyComp extends React.Component {
...
}
const MyCompWithLog = withLog(MyComp);
export const addComponent = data => {
return async function(dispatch) { // тут добавлен return и аргумент
let comps = await fire.database().ref("components");
comps.push({
name: data.component,
comp: data.component_name
});
//так же в любое время вы можете вызвать dispatch
dispatch({ type: 'someAction', payload: 'someValue' });
};
}
const foo = x => y => x + y;
const foo = x => {
return y => {
return x + y;
}
};
const foo = x => y => x + y;
const a = x(5);
const b = a(6);
console.log(b);
// => 11
y => 5 + y;
export const addComponent = data => async dispatch => {
let comps = await fire.database().ref("components");
// функция продолжит выполнение только когда вернется значение присвамваемое comps
comps.push({
name: data.component,
comp: data.component_name
});
};
class Child extends Component {
componentDidMount() {
this.props.callback();
}
render() {
return (
<div>Child</div>
);
}
}
class Parent extends Component {
onChildDidMount = () => {
console.log('Child component was mounted!');
// do something else
};
render() {
return(
<Wrapper>
<Child callback={this.onChildDidMount} />
</Wrapper>
);
}
}
render() {
const isUserInfoFormActive = ...; // your conditions
const isUserAddressFormActive = ...; // your conditions
return (
<Wrapper>
{isUserInfoFormActive && <UserInfoForm />}
{isUserAddressFormActive && <UserAddressForm />}
</Wrapper>
);
}
class FormWidget extends Component {
...
getContent() {
const { children, activeStep } = this.props;
return React.Children.map(children, (child, i) => {
if (activeStep === i + 1) {
return React.cloneElement(child, { key: i });
}
return null;
});
}
handleNext = () => {
...
};
handlePrev = () => {
...
};
render() {
...
return(
<div>
<Content>{this.getContent()}</Content>
<div>
<Button onClick={this.handlePrev}>{prevButtonLabel}</Button>
<Button onClick={this.handleNext}>{nextButtonLabel}</Button>
</div>
</div>
);
}
}
render() {
return (
<FormWidget>
<Step1 />
<Step2 />
<Step3 />
<Step4 />
<Step5 />
<Step6 />
<Step7 />
<Step8 />
<Step9 />
<Step10 />
</FormWidget>
);
}
this.state.title.map((item, i) => (
<TodoList
key={i}
index={i}
deleteItem={descriptionArr[i]}
title={titleArr[i]}
deleteItem={this.deleteItem}
/>
))
[
{
title: 'title',
description: 'description',
},
{
title: 'title',
description: 'description',
},
{
title: 'title',
description: 'description',
}
]
var data = this.props.data
class Example extends React.Component {
render() {
return <span>{this.props.someValue}</span>;
}
}
function Example (props) {
return <span>props.someValue</span>;
}
#root
= javascript_pack_tag 'SearchUsers', {data: @users.to_json(only: [:id, :name, :email]) }
import React, {Component} from 'react';
import PropTypes from "prop-types";
import ReactDOM from 'react-dom';
let data = []; // задаем значение по-умолчанию
try {
data = JSON.parse(document.querySelector('script[data]').getAttribute('data'));
} catch(e) {
console.log(e); // тут можно обработать ошибку парсинга данных
}
const User = ({ name, email }) => (
<section id={name}>
<h1> {name} </h1>
<h2> {email} </h2>
</section>
);
const Users = ({ user }) => (
<div className="users">
{user.map(user =>
<User key={user.id} {...user} /> // обратите внимание, заменено значение свойства key
)}
</div>
);
ReactDOM.render(
<Users user={data} />,
document.getElementById('root')
);
createCheckboxes = () => {
const data = this.props.pets[0] || {};
const newAnimals = Object.values(data).map(el => el.animal);
this.setState(({ animals }) => ({
animals: [ ...animals, ...newAnimals ],
}));
};
let counterReducer = (state=initialState, action) => {
let newstate = { ...state };
switch(action.type){
case "INC":
newstate.counter+=action.payload
return newstate
case "DEC":
newstate.counter+=action.payload
return newstate
default:
return newstate
}
}