Возможно, я сумасшедший, но я пытаюсь изучить ReachJs, Redux и Typescript одновременно. В основном потому, что проект шаблона Visual Studio использует все три, и я также хотел бы изучить все три.
Я действительно изо всех сил пытаюсь понять, как я передаю состояние от родительского компонента дочерним компонентам.
В моем примере у меня есть компонент счетчиков, который просто хочет перечислить несколько компонентов счетчика. Может ли кто-нибудь пролить свет, или есть ли где-нибудь примеры любых образцов проектов, которые я мог бы загрузить, которые имеют все три из react-redux и typescript - я изо всех сил пытаюсь найти много примеров со всеми тремя.
Я могу визуализировать один компонент счетчика самостоятельно, но как только я пытаюсь визуализировать несколько с родительским компонентом, я получаю ошибки.
Вот мой Counters.tsx
import * as React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as CountersStore from '../store/Counters';
import { Counter } from './Counter';
type CountersProps =
CountersStore.CountersState
& typeof CountersStore.actionCreators
& RouteComponentProps<{}>;
class Counters extends React.Component<CountersProps, {}> {
public render() {
return <div className = "m-2">
{this.props.counters.map(x => <Counter props = "x"/>)}
</div>;
}
}
// Wire up the React component to the Redux store
export default connect(
(state: ApplicationState) => state.counters, // Selects which state properties are merged into the component's props
CountersStore.actionCreators // Selects which action creators are merged into the component's props
)(Counters) as typeof Counters;
Вот мой Counters.ts
import { Action, Reducer } from 'redux';
import * as Counter from './Counter';
export interface CountersState {
counters: Counter.CounterState[]
}
interface DeleteCounterAction { type: 'DELETE_COUNTER', payload: number }
type KnownAction = DeleteCounterAction;
export const actionCreators = {
increment: (valueCount: any) => <DeleteCounterAction>{ type: 'DELETE_COUNTER', payload: valueCount },
};
export const reducer: Reducer<CountersState> = (state: CountersState, incomingAction: Action) => {
const action = incomingAction as DeleteCounterAction;
switch (action.type) {
case 'DELETE_COUNTER':
return { counters: [] };
}
return state || { counters: [] };
};
Вот мой Counter.tsx
import * as React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';
type CounterProps =
CounterStore.CounterState
& typeof CounterStore.actionCreators
& RouteComponentProps<{}>;
export class Counter extends React.Component<CounterProps, {}> {
public render() {
return <div className = "m-2">
<span>{this.props.Text}</span>
<span className = {this.getBadgeClasses()}>{this.formatCount()}</span>
<button className = "btn btn btn-primary btn-sm m-2" onClick = {() => { this.props.increment(2) }}>Increment</button>
<button className = "btn btn-danger btn-sm m-2" onClick = {() => { this.props.increment(3) }}>Delete</button>
</div>;
}
formatCount() {
const currentCount = this.props.count;
return currentCount === 0 ? "Zero" : currentCount;
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.props.count === 0 ? "warning" : "primary";
return classes;
}
}
// Wire up the React component to the Redux store
export default connect(
(state: ApplicationState) => state.counter, // Selects which state properties are merged into the component's props
CounterStore.actionCreators // Selects which action creators are merged into the component's props
)(Counter) as typeof Counter;
вот мой Counter.ts
import { Action, Reducer } from 'redux';
export interface CounterState {
count: number;
Text: string;
}
interface IncrementCountAction { type: 'INCREMENT_COUNT', payload: number }
interface DecrementCountAction { type: 'DECREMENT_COUNT', payload: number }
type KnownAction = IncrementCountAction | DecrementCountAction;
export const actionCreators = {
increment: (valueCount: any) => <IncrementCountAction>{ type: 'INCREMENT_COUNT', payload: valueCount },
decrement: (valueCount: any) => <DecrementCountAction>{ type: 'DECREMENT_COUNT', payload: valueCount },
};
export const reducer: Reducer<CounterState> = (state: CounterState, incomingAction: Action) => {
const action = incomingAction as KnownAction;
switch (action.type) {
case 'INCREMENT_COUNT':
return { count: state.count + action.payload, Text: state.Text + action.payload.toString() };
case 'DECREMENT_COUNT':
return { count: state.count - action.payload, Text: state.Text };
default:
const exhaustiveCheck: never = action;
}
return state || { count: 0, Text: "Hello" };
};
Разве это не похоже на то, что должен делать Redux, в отношении состояния и передачи различным компонентам, которые в этом нуждаются?
Контекст против Redux Плюсы -Просто реализовать -Вес и производительность -Возврат действия очистки с фрагментом состояния (как в setState) Минусы Работает только с React ^ 16.3 --- взято из medium.freecodecamp.org/…
Хорошо, спасибо - проверим, спасибо



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы проверили React Context? Похоже, это может вас заинтересовать: responsejs.org/docs/context.html и youtube.com/watch?v=XLJN4JfniH4