const allCars = {
bmw: [
{ name: 'x1', ... },
...
],
...
}
render() {
const { mark } = this.props;
const models = allCars[mark];
return (
<div>
{mark && (
<div>
<label>{mark}</label>
{models.map(model => (
<div key={model.name}>
<label>{model.name}</label>
<input
name="model"
value={model.name}
type="checkbox"
onClick={this.props.changemodel}
/>
</div>
))}
<div>
)}
</div>
);
}
changeMark (e) {
const { value } = e.target;
this.setState({
mark: value === 'all' ? [] : [...prevState.mark, value],
model: [],
page: 1,
});
}
}
handleCheckboxCheck(e) {
const { name, value } = e.target;
this.setState(prevState => ({
[name]: _.xor(prevState[name], +value),
}));
}
constructor(props) {
super(props);
this.changeModel = this.changeModel.bind(this);
}
changeModel (e) {
// some actions
}
changeModel = e => {
// some actions
};
{this.state.data[0].title}
render() {
const { data } = this.state;
const isAllDataReady = data && data.length > 0;
return (
<div>
{!isAllDataReady && <Preloader />}
{isAllDataReady && (
<div>
<h4>App component</h4>
{data[0].title}
</div>
)}
</div>
);
}
Cannot convert undefined or null to object
import React from 'react';
import { connect } from 'react-redux';
export class Balance extends React.Component {
// some code
}
const mapStateToProps = ({ total }) => ({ total });
export default connect(mapStateToProps)(Balance);
import { Balance } from './Balance';
import Balance from './Balance';
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import { Balance } from '../app/containers/balance/src/balance';
describe('<Balance />', () => {
it('Balance test', function () {
const mockTotal = { /* mock code */ };
const wrapper = shallow(<Balance total={mockTotal} />);
expect(wrapper.contains(<h3>Мои балансы</h3>)).to.equal(true);
});
});
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tweets: []
};
}
getData = () => {
axios.post('/', {
username: this.state.username
})
.then(({data: tweets}) => {
console.log(tweets)
this.setState({ tweets });
})
.catch(console.error);
};
render () {
const { tweets } = this.state;
console.log(tweets.length);
if (tweets.length > 0 && tweets[0].user) {
console.log(tweets.length);
return (
<div>
<header>
<Form getData={this.getData} />
</header>
<main>
<User user={tweets[0].user} />
{tweets.map((tweet, i) => <Tweet key={i} tweet={tweet} />)}
</main>
</div>
);
} else {
return (
<Form getData={this.getData} />
);
}
}
}
constructor(props) {
super(props);
this.state = {
tweets: []
};
this.getData = this.getData.bind(this);
}
class Capture extends React.Component {
constructor(props) {
super(props);
this.state = {
form: {
username: '',
},
tweets: [],
}
this.onFormSubmit = this.onFormSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
onFormSubmit(e) {
e.preventDefault()
axios.post('/', {
username: this.state.form.username
})
.then(({data: tweets}) => {
this.setState({ tweets });
})
.catch(console.error);
}
handleChange(event) {
const { form } = this.state;
form.username = event.target.value;
this.setState({ form });
}
render () {
const { tweets } = this.state;
return (
<div>
<form onSubmit={this.onFormSubmit}>
<p className="leadform-component-container">
<input
type="text"
placeholder="Username"
required
onChange={this.handleChange}
/>
</p>
<p className="leadform-component-container">
<input type="submit" value="Press me" />
</p>
</form>
<div>
{tweets.map((tweet, i) => <Tweet key={i} tweet={tweet} />)}
</div>
</div>
)
}
}
ReactDOM.render(<Capture />, document.getElementById("app"));
clickHandle(e) {
// some code
}
clickHandle = e => {
// some code
};
constructor(props) {
super(props);
this.clickHandle = this.clickHandle.bind(this);
}
<SomeComponent onClick={() => this.сlickHandle()} /> // контекст не будет потерян
<ListItem
key={item.id}
onClick={e => this.сlickHandle(item.id, e)}
>
{item.name}
</ListItem>
var john = {
firstName: 'John',
getName() {
return this.firstName; // this - контекст вызова и это не всегда наш объект
}
}
console.log(john.getName()); // john
var foo = {
firstName: 'foo',
};
var foo.getName = john.getName;
console.log(foo.getName()); // foo
var bar = john.getName;
console.log(bar()); // undefined
Cannot read property 'firstName' of undefined
<Route path="/stories/:slug" component={Stories}/>
const mapStateToProps = state => {
return {
items: state.items.items,
error: state.items.error,
loading: state.items.loading
};
};
export function items(state = initialState, action) {
const { type, payload } = action;
switch (type) {
// some code
case "FETCH_SUCCESS":
return {
...state,
items: [ ...state.items, ...payload.items ],
loading: false,
};
// some code
}
}
export const fetchProductsBegin = () => ({ type: FETCH_BEGIN });
const mapStateToProps = state => ({
items: state.items.items,
error: state.items.error,
loading: state.items.loading,
});
{cont.continents.map(el => (
<li key={el.code}>{el.name}</li>
))}
render() {
const { res } = this.state;
const shouldFlimDisplayShown = !!res;
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="title">Enter title</label>
<input id="title" name="title" type="text" />
<button>Send data!</button>
</form>
{shouldFlimDisplayShown && <FilmDisplay filmName={res}/>}
</div>
);
}
import React from 'react';
class FilmDisplay extends React.Component {
constructor() {
super();
this.state = {
filmData: null
};
}
componentDidMount() {
this.fetchMovie();
}
componentDidUpdate(prevProps) {
if (prevProps.filmData !== this.props.filmData) {
this.fetchMovie();
}
}
fetchMovie() {
const { filmName } = this.props;
const URL = "http://www.omdbapi.com/?t=" + filmName + "&apikey=6540f2ec&";
fetch(URL).then(res => res.json()).then(json => {
this.setState({ filmData: json });
});
}
render() {
const { filmData } = this.state;
if (!filmData) return <div>Loading</div>;
return <div>{JSON.stringify(filmData)}</div>;
}
}
export default FilmDisplay;
render() {
const { _sharedData: { auth_user } } = this.props;
const shouldShowIconMenu = +auth_user === 1;
return (
<AppBar>
{shouldShowIconMenu && (
<IconMenu>
...
</IconMenu>
)}
</AppBar>
);
}
<div id={if (condition) { 'msg' }}>Hello World!</div>
React.createElement("div", { id: if (condition) { 'msg' } }, "Hello World!");
const ProductsList = ({
productsList,
checkIsProductAddedToCart,
}) => (
<ul>
{productsList.map(product => (
<Product
addedToCart={checkIsProductAddedToCart(product.id)}
product={product}
/>
))}
</ul>
);
const mapStateToProps(state => ({
productsList: productListSelector(state),
checkIsProductAddedToCart: checkIsProductAddedToCartSelector(state),
}));
export default connect(mapStateToProps)(ProductsList);
const mapStateToProps((state, ownProps) => ({
isAddedToCart: isProductAddedToCartSelector(state, ownProps),
}));
export default connect(mapStateToProps)(ProductDetails);
import { createSelector } from 'reselect';
const cartSelector = state => state.cart;
const cartProductsSelector = createSelector(
cartSelector,
cart => cart.products,
);
// возвращает функцию, принимающую id, которую можно использовать при построении списков
const checkIsProductAddedToCartSelector = createSelector(
cartProductsSelector,
products => id => products.some(product => product.id === id),
);
const productIdSelector = (_, props) => props.product.id;
// возвращает булево значение, важно чтобы в компоненте было свойство product
const isProductAddedToCartSelector = createSelector(
cartProductsSelector,
productIdSelector,
(products, id) => products.some(product => product.id === id),
);
class Parent extends Component {
state = {
text: 'some text',
};
handleClick = () => {
this.setState({ text: 'some other text'});
};
render() {
const { text } = this.state;
return (
<Wrapper>
<Button onClick={this.handleClick} />
<Text>{text}</Text>
</Wrapper>
);
}
}
const mapStateToProps = (state) => {
projects: state.projects
}
const mapStateToProps = (state) => ({
projects: state.projects
});