javascript - 在react redux中接收数据后调用另一个函数内部的函数
问题描述
如果我收到数据,如何在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;
待办事项
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);
解决方案
推荐阅读
- javascript - 将媒体查询动态添加到页面并覆盖来自应用程序端生成的 html 的样式
- python-3.x - 将时间增量转换为熊猫中连续时间点的整数
- php - 通过单击按钮 CodeIgniter 加载视图
- python - Python - 随机延迟调度
- python - python在字典中附加一个带有字典的数组
- dictionary - 如何在 Map 中找到最小元素并返回一个元组(键,最小元素)?
- excel - 为什么当我在 excel VBA 上运行这个宏时什么都没有发生?我错过了什么吗?
- html - 为什么我的第一行的高度大于其他行 HTML
- python - 如何在单个 Django 视图中跨多个模型进行查询?
- c++ - 我的程序无法正常工作,我的函数不断抛出分段错误