Как вызвать функцию getTodo
внутри функции getTodos
, если я получу данные. if (data) {getTodo ()}
? Ожидаемый эффект от click button
-> вызова функции getTodos
-> if (data) {getTodo ()}
.
Я пытаюсь вызвать getTodo ()
, как это в действиях:
.then (({data}) => {
dispatch ({type: GET_TODOS, payload:
date
});
}, () => getTodo ())
Демонстрация здесь: https://stackblitz.com/edit/react-iuvdna?file=actions%2Findex.js
действия
import axios from 'axios';
export const GET_TODOS = 'GET_TODOS';
export const GET_TODO = 'GET_TODO';
export const FETCH_FAILURE = 'FETCH_FAILURE';
export const getTodos = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos',
method: 'GET',
})
.then(({data})=> {
dispatch({type: GET_TODOS, payload:
data
});
},() => getTodo())
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
export const getTodo = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'GET',
})
.then(({data})=> {
dispatch({type: GET_TODO, payload:
data
});
})
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
редукторы
import {GET_TODOS, GET_TODO} from '../../actions';
import { combineReducers } from 'redux';
const todos = (state = [], action) => {
const { type, payload } = action;
switch (action.type) {
case 'GET_TODOS':
return payload;
default:
return state;
}
};
const todo = (state = {}, action) => {
const { type, payload } = action;
switch (action.type) {
case 'GET_TODO':
return payload;
default:
return state;
}
};
const rootReducer = combineReducers({
todos,
todo
});
export default rootReducer;
Todos
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos, clearTodos, getTodo} from '../.././actions';
class Todos extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<button onClick={this.props.getTodos}>Get Todos</button>
<ul>
{this.props.todos.map(todo => {
return <li key={todo.id}>
{todo.title}
</li>
})}
</ul>
{this.props.todo.id}
</div>
);
}
}
const mapStateToProps = state => {
const { todos, todo } = state;
return {
todos,
todo
};
};
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos()),
getTodo: () => dispatch(getTodo())
});
export default connect(mapStateToProps, mapDispatchToProps)(Todos);