在redux中更新状态

时间:2018-08-12 11:47:46

标签: reactjs redux

我是Redux的新手,大多数事情都有些模糊。例如在redux中更新状态。

考虑到这一点,我有一个容器叫websocket

componentDidUpdate() {
    var socket = openSocket('https://coincap.io');
    var updateCoinData = [...this.props.cryptoLoaded]; //
     socket.on('trades', (tradeMsg) => {  
      for (let i=0; i<updateCoinData.length; i++) {

        if (updateCoinData[i]["short"] == tradeMsg.coin ) {     

        //Search for changed Crypto Value 
        updateCoinData[i]['price'] = tradeMsg['message']['msg']['price']

        //Update the crypto Value state in Redux

          }
        }
     })
  }

在这里,我从websocket获取更改的数据,现在我想用新数据更新Redux的状态。

当我做这样的事情时,我正在从redux状态的上述代码片段中加密加载。

const mapStateToProps = state => {
  return {
    cryptoLoaded: state.posts.itemsSucess
   // cryptoIsloading: state.posts.cryptoIsloading
  }
};

export default connect(mapStateToProps, {fetchCoin})(cryptoTicker);

提取硬币中的数据通过操作

import axios from 'axios';
import {CRYPTO_FETCHING, CRYPTO_DATA_FAIL, CRYPTO_FETCH_SUCESS, UPDATE_CRYPTO_DATA} from './type.js';
import {ApiCoinCap} from '../urls.js';


export const fetchCoin = () => {
  return function (dispatch) {
    dispatch({type: CRYPTO_FETCHING})
    axios.get(ApiCoinCap).then((response) => dispatch({
      type: CRYPTO_FETCH_SUCESS,
      payload: response.data
    })).catch(error => dispatch({
      type: CRYPTO_DATA_FAIL,
      payload: error.data
    }))
  }
}

[问题]::如何调度动作以更新状态?

[更新:]这是我的异径管的外观

   import {CRYPTO_FETCHING, CRYPTO_DATA_FAIL, CRYPTO_FETCH_SUCESS} from './../actions/type.js';


const initialState = {
  itemsSomething : [],
  itemsSucess: [],
  itemsFail: []


}


export default function(state = initialState, action) {

  switch(action.type) {
    case CRYPTO_FETCHING:
    return {
      ...state,
      itemsSomething: action.payload
    }
    case CRYPTO_FETCH_SUCESS:
      return {
        ...state,
        itemsSucess: action.payload
      }
      case CRYPTO_DATA_FAIL:
      return {
      ...state,
      itemsFail: action.payload
    }
    default:
      return state
  }
}

后来我通过做这样的事情

import { combineReducers } from 'redux';
import postReducer from './postreducer';

const rootreducer = combineReducers({
  posts: postReducer
})

export default rootreducer

[回复:问题] 如何在Redux中更新现有状态?即我的网络套接字发送了我要在此处更新的数据

case CRYPTO_FETCH_SUCESS:
          return {
            ...state,
            itemsSucess: action.payload
          }

1 个答案:

答案 0 :(得分:0)

[问题]:如何调度动作以更新状态?

您可以使用react-redux库中的mapDispatchToProps函数来执行此操作,并且还需要redux thunk库中的异步操作创建者。

您的mapDispatchToProps函数将如下所示

function mapDispatchToProps (dispatch) {
  return {
    crypto_success: (res) => dispatch(ACTIONS.set_crypto(res)),
  }
}

ACTIONS.set_crypto()将是您必须在动作文件中定义的redux thunk,然后将其导入此处。像

import * as ACTIONS from **Location of your actions file**

您的axios获取请求应为

axios.get(ApiCoinCap)
 .then(res => this.props.crypto_success(res.data))

最后,动作创建者将是

export function set_crypto(data) {
  return dispatch => {
    dispatch({type: ACTION_TYPES.CRYPTO_FETCH_SUCESS, payload: data})
  }
}

您还需要修改根index.js文件,以使用redux thunk

import { Provider } from 'react-redux';
import rootReducer from './store/reducers/index';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';



let store = createStore(
                        rootReducer,
                        applyMiddleware(thunk)
                      )


ReactDOM.render(<Provider store={store}>
                  <App />
                </Provider>,
                document.getElementById('root'));

就这样,您现在应该能够保存来自axios调用redux的数据。