gpt4 book ai didi

ajax - 如何在redux中发出AJAX请求

转载 作者:行者123 更新时间:2023-12-03 12:54:48 25 4
gpt4 key购买 nike

据我所知,我必须在创建操作中编写请求。如何在行动中使用 promise 来提交请求?我正在获取实际数据。然后在reducer中创建新的状态。连接中绑定(bind) Action 和 reducer 。但我不知道如何使用 Promise 来请求。

行动

import $ from 'jquery';
export const GET_BOOK = 'GET_BOOK';

export default function getBook() {
return {
type: GET_BOOK,
data: $.ajax({
method: "GET",
url: "/api/data",
dataType: "json"
}).success(function(data){
return data;
})
};
}

reducer

import {GET_BOOK} from '../actions/books';

const booksReducer = (state = initialState, action) => {
switch (action.type) {
case GET_BOOK:
return state;
default:
return state;
}
};

export default booksReducer;

容器如何在容器中显示数据?

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import getBook from '../actions/books';
import Radium from 'radium';
import {Link} from 'react-router';

function mapStateToProps(state) {
return {
books: state.data.books,
};
}

function mapDispatchToProps(dispatch) {
return {
getBooks: () => dispatch(getBook()),
};
}

@Radium
@connect(mapStateToProps, mapDispatchToProps)
class booksPage extends Component {
static propTypes = {
getBooks: PropTypes.func.isRequired,
books: PropTypes.array.isRequired,
};

render() {
const {books} = this.props;
return (
<div>
<Link to={`/authors`}><MUIButton style="flat">All Authors</MUIButton></Link>
<ul>
{books.map((book, index) =>
<li key={index}>
<Link to={`/book/${book.name}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4">
"{book.name}"</div></MUIButton></Link>
<Link to={`/author/${book.author}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4">
{book.author}</div></MUIButton></Link>
</li>
)}
</ul>
</div>
);
}
}

export default booksPage;

最佳答案

由于您已经在使用 redux,因此您可以应用 redux-thunk 中间件,它允许您定义异步操作。

安装与使用:Redux-thunk

export function fetchBook(id) {
return dispatch => {
dispatch(setLoadingBookState()); // Show a loading spinner
fetch(`/book/${id}`, (response) => {
dispatch(doneFetchingBook()); // Hide loading spinner
if(response.status == 200){
dispatch(setBook(response.json)); // Use a normal function to set the received state
}else {
dispatch(someError)
}
})
}
}

function setBook(data) {
return { type: 'SET_BOOK', data: data };
}

关于ajax - 如何在redux中发出AJAX请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com