标签: redux-thunk

如何在等待redux解析时禁用按钮?

在以下示例中,如何在地理定位请求期间禁用按钮?在this.props.inProgress没有在init上设置,我想在请求getCurrentPosition时禁用按钮,如果解决了RECEIVE_LOCATION则启用.什么是正确的方法?我是否要将状态和复制道具用于GeoButton?

export function getGeolocation() {
  return dispatch => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        dispatch({
          type: 'RECEIVE_LOCATION',
          coords: {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            inProgress: false,
          },
        });
      });
    }
  }
}
export function geolocation(state={}, action) {
  switch (action.type) {
    case 'RECEIVE_LOCATION':
      var newState = action.coords;

      return newState;
    default:
      return state;
  }
}


class GeoButton extends React.Component {
  constructor(props) {
    super(props);
  }

  findLocation(e) {
    e.preventDefault();
    this.props.dispatch(getGeolocation());
  }
  render() {
    console.log(this.props); // on init geolocation object is empty
    var self = this; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs redux redux-thunk

3
推荐指数
1
解决办法
2101
查看次数

dispatch 不是函数 TypeError

我是 react-redux 的新手,我正在使用 react-thunk 中间件。每当我尝试运行我的动作创建者(通过按下我的按钮)时,我都会收到错误“未捕获的类型错误:调度不是函数”。有谁知道这是怎么回事?

源代码/操作/index.js

function editUserName (newUserName) {
    return {
        type: 'CHANGE_USER_NAME',
        newUserName: newUserName
    }
}

export function editUserNameDelegate () {
    return function (dispatch, getState) {
        return dispatch(editUserName("thunkUser"))
    }
}
Run Code Online (Sandbox Code Playgroud)

src/容器/admin.js

import { editUserNameDelegate } from '../actions/index'
...
<input type="button" onClick={ editUserNameDelegate() } value="edit UserName" />
Run Code Online (Sandbox Code Playgroud)

javascript reactjs redux redux-thunk react-redux

3
推荐指数
1
解决办法
9922
查看次数

来自组件 react/redux 的多次调度调用

我真的不知道为什么我不能让它工作。所有的证据都反对它......情况是这样的:

我有一个数据网格和一个搜索面板。当搜索面板更改时,搜索参数会更新并用于更新数据网格。

触发链的事情是当用户更改搜索面板时。在我的组件中,我通过以下方式处理搜索面板更改:

  getPhotos(key, value) {
    const change = [{ key: key, value: value},{ key: 'page', value: 1}]
    this.props.dispatch(updateSearchParams(change))

    console.log('payload.searchParams', this.props.searchParams);

    this.props.dispatch(
      getPhotos(
        { context:this.props.params.context,
          searchParams: this.props.searchParams }
      )
    );
  }
Run Code Online (Sandbox Code Playgroud)

因此,对动作创建者的两个调度调用形成了组件。问题是 searchparams 没有及时更新 getPhotos 调用,因此网格没有相应更新。

我认为调度调用是同步的——因此一个接一个。我想这是从组件到动作创建者,再到存储和减速器的往返行程,它“搞砸”了它。第一次调用不涉及任何异步调用。

这样做的“正确”方法是什么?请具体说明组件、动作创建者和减速器中的内容。

谢谢

reactjs redux redux-thunk

3
推荐指数
1
解决办法
2966
查看次数

同时应用applyMiddleware(thunk)获取"无法将类作为函数调用",在react js中

这是我的index.js文件代码 -

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'; 
import { Provider } from 'react-redux';
import thunk from 'react-thunk';
import { createStore, applyMiddleware } from 'redux';
import Login from './Components/LoginRegister';

const store= createStore(
        (state = {}) => state, 
        applyMiddleware(thunk)
    );

ReactDOM.render(( 
    <Provider store={store}>
      <Router>
        <switch>
            <Route exact path="/" component={App} />
            <Route path="/Loginregister" component={Login} />
        </switch>
      </Router>
    </Provider>  ),
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

因为我在'applyMiddleware'中传递'thunk'作为'applyMiddleware(thunk)'然后我在控制台上得到以下错误 -

Uncaught TypeError: …
Run Code Online (Sandbox Code Playgroud)

reactjs redux-thunk

3
推荐指数
1
解决办法
1730
查看次数

在Redux Reducer中执行Ajax Fetch?

我正试图绕过Redux actionCreators中的状态; 而是执行以下操作(在reducer中执行ajax操作).为什么我需要为此访问状态 - 因为我想使用存储在状态中的CSRF令牌执行ajax.

有人可以告诉我,如果以下被认为是不良做法/反模式?

export const reducer = (state = {} , action = {}) => {

    case DELETE_COMMENT: {

        // back-end ops
        const formData = new FormData();
        formData.append('csrf' , state.csrfToken);
        fetch('/delete-comment/' + action.commentId , {
            credentials:'include' ,
            headers:new Headers({
                'X-Requested-With':'XMLHttpRequest'
            }) ,
            method:'POST' ,
            body:formData
        })

        // return new state
        return {
            ...state ,
            comments:state.comments.filter(comment => comment.id !== action.commentId)
        };
    }

    default: {
        return state;
    }
}
Run Code Online (Sandbox Code Playgroud)

redux redux-thunk

3
推荐指数
1
解决办法
2016
查看次数

mapStateToProps中的状态是JSX!React/Redux

我是React/Redux的初学者并遇到了这个疯狂的问题,当我在console.log状态下调试mapStateToProps(状态)时,它记录了一些JSX.详细说明...

import React, { Component } from 'react';
import { connect } from 'react-redux';

import BlogListItem from './blog_list_item';
import selectBlogs from '../selectors/blogs';

const BlogList = (props) => (
    <div className="content-container">
        <div className="list-header">
            <div className="show-for-mobile">Blogs</div>
            <div className="show-for-desktop">Blog</div>
            <div className="show-for-desktop">Posted on</div>
        </div>
        <div className="list-body">
            {
                props.blogs.length === 0 ? (
                    <p className="list-item list-item--message">No Blogs. Write one now!</p>
                ) : (
                    props.blogs.map((blog) => {
                        return <BlogListItem key={blog.id} {...blog} />;
                    })
                )
            }
        </div>
    </div>
);

const mapStateToProps = (state) => {
    console.log(state); // …
Run Code Online (Sandbox Code Playgroud)

reactjs redux redux-thunk react-redux

3
推荐指数
1
解决办法
72
查看次数

React native router flux:TypeError:undefined不是函数(评估'addListener')

我使用这个主要依赖项工作在本机应用程序上:

  • 反应原生
  • 反应原生路由器通量
  • 做出反应
  • 博览会

我正在使用这个package.json:

"dependencies": {
    "expo": "23.0.4",
    "humps": "^2.0.0",
    "install": "^0.10.1",
    "lodash": "^4.17.4",
    "native-base": "^2.3.5",
    "react": "16.0.0",
    "react-native": "0.50.4",
    "react-native-extend-indicator": "^0.1.2",
    "react-native-keyboard-aware-scroll-view": "^0.4.2",
    "react-native-maps": "^0.19.0",
    "react-native-maps-directions": "^1.3.0",
    "react-native-modal-datetime-picker": "^4.13.0",
    "react-native-qrcode": "^0.2.6",
    "react-native-router-flux": "4.0.0-beta.24",
    "react-native-svg-uri": "^1.2.3",
    "react-native-swiper": "^1.5.13",
    "react-native-vector-icons": "^4.4.2",
    "react-navigation-redux-debouncer": "^0.0.2",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0",
    "swagger-client": "2.1.32"
  }
Run Code Online (Sandbox Code Playgroud)

应用程序正在使用expo所以我使用以下命令安装依赖项:

  • 纱线安装

然后运行应用程序

  • yarn start --reset-cache

我工作正常,因为我想添加一个新的依赖项,所以我删除了node_modules文件夹和yarn.lock文件,添加了新的依赖项并再次执行yarn安装.

之后,我在打开应用程序时遇到此错误:

TypeError:undefined不是函数(评估'addListener')

在此输入图像描述

它与react-navigation有关,但我使用的是react-native-router-flux 4.0.0-beta.24,它在内部使用react-navigation ^ 1.0.0-beta.19.

我最近注意到使用react-navigation的人对此有一些麻烦(https://github.com/react-navigation/react-navigation/issues/3416)但使用beta.28版本.

如果我回到之前的node_modules文件夹(从垃圾箱)我的应用程序运行良好,所以..可能是因为我的package.json 的^符号的某些依赖性不再兼容..也许thunk或反应本机路由器与我的反应本机版本的通量.

有任何想法吗?

当我使用react thunk中间件时,这是代码的一部分:

import {applyMiddleware, …
Run Code Online (Sandbox Code Playgroud)

react-native redux redux-thunk react-native-router-flux react-navigation

3
推荐指数
1
解决办法
3528
查看次数

修改Redux Store时组件未更新

我正在使用redux thunk来返回操作的API调用:

export const getActiveCampaigns = () => {
return (dispatch, getState) => {
    const bearer = 'Bearer ' + getState().login.bearer
    return axios.get(API.path + 'campaign/active/?website_id=' + getState().selectedWebsite.selectedWebsite + '&' + API.beaconAPI_client, { headers: { 'Authorization': bearer } })
    .then(function (response) {
        dispatch({
            type: GET_ACTIVE_CAMPAIGNS,
            activeCampaigns: response.data.response
        })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

这样做的原理是成功返回广告系列列表,我使用以下命令将其渲染到另一个组件中:

class ActiveCampaignsDropdown extends Component {
    // usual stuff

    componentDidMount(){
        this.props.dispatch(getActiveCampaigns())
    }

    // render function displays campaigns using this.props.activeCampaigns
}

const mapStateToProps = (state) => {
    return {
        activeCampaigns: state.activeCampaigns.activeCampaigns …
Run Code Online (Sandbox Code Playgroud)

reactjs redux redux-thunk

3
推荐指数
1
解决办法
8046
查看次数

从服务器获取api获取错误消息,而不是一般消息

我正在使用redux thunk在操作中获取一些数据

function handleErrors(response) {
    console.log(response)
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

export const something = (var) => dispatch => {
    fetch(`${url}/something`, {credentials: 'include'})
    .then(handleErrors)
    .then(res => res.json())
    .then(res =>
        dispatch({
            type: SOMETHING,
            payload: res
        })
    )
    .catch(error => 
        dispatch({
            type: ERROR,
            payload: error
        })
    )
Run Code Online (Sandbox Code Playgroud)

我的快递服务器上的错误响应为“某些错误”

return res.status(500).send({ message: 'some error' });
Run Code Online (Sandbox Code Playgroud)

当它获取并且是错误(500)时,其消息是通用的“内部服务器错误”。

如何获取提取中的“某些错误”?

javascript redux fetch-api redux-thunk react-redux

3
推荐指数
1
解决办法
325
查看次数

如何解决“动作必须是普通对象。将自定义中间件用于异步动作。]”?

因此,我在此上浪费了5个小时。

我有一个redux thunk动作,如下所示:

export const fetchUser = () => async (getState, dispatch) => {
  if (getIsFetching(getState().user)) {
    return Promise.resolve();
  }

  dispatch(fetchUserRequest());

  try {
    const response = await api.fetchUser();

    dispatch(fetchUserSuccess({ userObject: { ...response } }));
  } catch (error) {
    dispatch(fetchUserFailure({ message: "Could not fetch user profile." }));
  }
};
Run Code Online (Sandbox Code Playgroud)

调用它总是结束于“操作必须是普通对象。将自定义中间件用于异步操作。]”。

好,当然。我已经在使用redux-thunk了,为什么它一直困扰着我?

注意:fetchUserRequest(),fetchUserSuccess()和fetchUserFailure()都返回简单的普通redux操作。

redux-thunk

3
推荐指数
2
解决办法
5743
查看次数