Redux.js - 我无法使用 React Redux 映射StateToProps - 我的 React 组件块在商店初始状态上并且在 store.state 更新时无法更新 [英] Redux.js - I fail to mapStateToProps with React Redux - My React Component block on the store initial state and fail to update when store.state update

查看:48
本文介绍了Redux.js - 我无法使用 React Redux 映射StateToProps - 我的 React 组件块在商店初始状态上并且在 store.state 更新时无法更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将包含的 app.state 传递到 React 组件中的 Redux 存储.

到目前为止,这个问题仍然是一个很深的谜......

------> 这里是我代码的 GITHUB 存储库 <------

希望它有助于找出问题所在.

摘要:

我的问题基本上是关于 mapStateToProps,是关于将一​​个组件链接到状态存储,AFAIK 其余的工作非常好,但是 在 React 中,我的 this.props 似乎有些捷径组件,因为要么我使用connect()要么删除mapStateToProps方法,我的组件仍然显示初始状态..!

Redux 像一个终端级别的老板一样抵制我......

<小时>

游戏状态

  • 拥有 react-redux 存储的提供者:好的
  • 连接函数传递给道具:OK
  • mapDispatchToProps 工作正常!那么,既然连接似乎已经建立,那么为什么状态无法更新道具呢?
    • 我知道我的操作被很好地映射了,因为当我删除连接组合中的 mapDispatch 时,该组件无法触发相应的操作.
  • 当 console.log 时,mapState 有效地接收商店更新,但组件在初始状态下保持阻塞状态(使用返回store.getState().propertyTargeted"的组件上的checkState"按钮进行测试)

提示:

  • 当我删除connect中的mapStateToProps时,我的React.Component继续接收initialState,所以也许有另一个来源覆盖了我的 mapStateToProps,我目前正在寻找它
  • 我的 this.props.state 变量在组件的构造函数中被调用,也许构造函数没有收到 store.updateState 或类似的东西?另一条轨道.

这里是我的 combineReducer.js :

import { combineReducers } from "redux";从./status"导入{post}从./updateState"导入{entry};//只有一个减速器处于活动状态const appReducer = combineReducer({入口,邮政})导出默认的 appReducer

这里是我的 container.js :

const mapStateToProps = (state) =>{返回{字:state.entry.word}}const mapDispatchToProps = {postFile: postFileAction}const PostFileContainer = connect(mapStateToProps, mapDispatchToProps)(Component) ;

我的 postFile.js :

export const postFile = (word, base64Data) =>调度 =>{console.log("postFile httpRequest 到达")派遣({类型:'POST_WORD',状态:请求});axios.post("http://localhost:7500/api/files", {词":词,数据":base64Data}, {内容类型":多部分/表单数据"}).then(res =>派遣({类型:'POST_WORD',状态:成功,资源})).catch(错误 => {派遣({类型:'POST_WORD',状态:错误,呃})});}

在我的 store.initialState 中:

初始状态:{邮政": {},入口": {词":初始词"}}

UPDATE_STATE_POSTWORD 是由其他 React 组件提供的,因此在窃听组件使用更新的单词条目触发它自己的操作之前被分派到商店.这是我的 UPDATE_STATE_POSTWORD 操作片段:

export const updateWord = word =>{返回 {类型:UPDATE_STATE_POSTWORD,单词};}

///reducers.js 部分///

postReducer.js:

 export const post = (state ={}, action) =>{console.log("postStatus 到达 - 减速器")开关(动作.状态){案例请求:console.log("请求开始")返回状态案例成功:开关(动作.类型){案例 POST_FILE:console.log("请求成功:", action.res)var _id = action.res._id//var word= action.res.wordreturn (Object.assign({}, state, {_ID}))案例 POST_WORD:console.log("请求成功:", action.res)返回 (Object.assign({}, state, {_ID: ""}))默认 :console.log(`成功案例中的默认状态postStatusReducer`)返回状态}案例错误:console.log("请求错误:", action.err)返回状态默认:返回状态}}

entryReducer.js:

 const initialState = { word : "initialWord" }export const updateStateReducer = (state= initialState, action) =>

{

 开关 (action.type) {案例 UPDATE_STATE_POSTWORD:var word = action.wordreturn (Object.assign({}, state, {单词}))默认:返回状态}}

谢谢

解决方案

如果你使用 react-thunk,你的 action fn 会收到 dispatchgetState 函数作为参数.运行 getState 将为您提供应用程序的实际状态.回收的数据会传递给reducer等等.

在您的示例中,RecordingAPI 仅在初始化时接收来自 redux 的道具 - 在构造函数中.您可以通过添加 componentWillReceiveProps 方法

来修复您的组件

class RecordingAPI 扩展 React.Component {构造函数(道具){超级(道具);...this.state = {词 : this.props.word,状态:this.props};}//监听 props 的新方法componentWillReceiveProps(道具){this.setState({词:this.props.word,状态:this.props});}检查状态(e){e.persist();e.preventDefault();e.stopPropagation();console.dir(this.state.word)控制台.dir(this.state.state)}使成为() {...返回 (<div><button onClick={(e) =>this.checkState(e)}>CheckState </button>

);}}

I'm trying currently to pass the app.state contained to the Redux store in a React Component.

So far, this problem is still a deep mystery...

------> HERE THE GITHUB REPOSITORY OF MY CODE <------

Hope it will help to figure out what is wrong.

Abstract :

My problem is basically about mapStateToProps, is about link a Component to the state store, AFAIK the rest work very fine, but Something seems shortcut my this.props in React's Component, because either I use connect() or delete the mapStateToProps method, my Component stil display the initial state ..!

Redux resists me like an end-level's boss...


STATE OF PLAY

  • The provider with a store of react-redux: OK
  • Connect function pass to the props: OK
  • mapDispatchToProps works fine! So why the state fails to update the props since the connection seems well established?
    • I know my action is well mapped since when I delete the mapDispatch in the connect composition, the component then fails to trigger the corresponding action.
  • When console.log, the mapState receive effectively the store update but the Component stay blocked on initial state (tested with a "checkState" button on the component which returns the "store.getState().propertyTargeted"

HINTS :

  • when I delete the mapStateToProps in connect, my React.Component continue to receive the initialState, so maybe there is an another source that overwrites my mapStateToProps, I seek for it currently
  • my this.props.state variable is called in the Component's constructor, maybe the constructor doesn't receive the store.updateState or something like that ? Another track to follow.

Here my combineReducer.js :

import { combineReducers } from "redux";

import {post} from "./status"
import {entry}from "./updateState";

// only one reducer active 
const appReducer = combineReducers({ 
    entry,
    post

})
export default appReducer

Here my container.js :

const mapStateToProps = (state) => {

  return { word: state.entry.word }
}

const mapDispatchToProps = {
     postFile: postFileAction  
}

const PostFileContainer = connect(mapStateToProps, mapDispatchToProps)(Component) ;

My postFile.js :

export const postFile = (word, base64Data) => dispatch => {
  console.log("postFile httpRequest reached")

  dispatch({
    type: 'POST_WORD',
    status: request
  });
  Axios.post("http://localhost:7500/api/files", {
      "word": word,
      "data": base64Data

    }, {
      "Content-Type": "multipart/form-data"
    })
    .then(res =>
      dispatch({
        type: 'POST_WORD',
        status: success,
        res
      }))
    .catch(err => {
      dispatch({
        type: 'POST_WORD',
        status: error,
        err
      })
    });


}

Here in my store.initialState :

initial state: {
  "post": {},
  "entry": {
    "word": "initialWord"
  }
}

the UPDATE_STATE_POSTWORD is provide by an other React component therefore dispatched to the store before that the bugging component trigger it own action with a updated word's entry. Here my UPDATE_STATE_POSTWORD action snippet :

export const updateWord = word => {
  return {
    type: UPDATE_STATE_POSTWORD,
    word
  };
} 

/// reducers.js part ///

postReducer.js :

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

  console.log("postStatus reached - reducer")
    switch (action.status) {
      case request:
        console.log("Request start")
        return state
      case success:
        switch (action.type) {
          case POST_FILE:
            console.log("request succeed: ", action.res)

            var _id = action.res._id
            // var word= action.res.word
            return (Object.assign({}, state, {
              _id 
            }))
          case POST_WORD:
            console.log("request succeed: ", action.res)
            return (Object.assign({}, state, {
              _id: ""
            }))
          default : 
            console.log(`default state on success case in
                         postStatusReducer`)
            return state
      }
      case error:
        console.log("request error: ", action.err)
        return state
      default:
        return state
    }

}

entryReducer.js :

 const initialState = { word : "initialWord" }
 export const updateStateReducer = (state= initialState, action) => 

{

    switch (action.type) {
        case UPDATE_STATE_POSTWORD:
            var word = action.word
            return (Object.assign({}, state, {
                word
            }))
        default:
            return state

    }
}

Thanks

解决方案

If you are using react-thunk, your action fn would receive dispatch and getState functions as arguments. Running getState would give you actual state of the application. Recuired data would be passed to reducer and so on.

In your example RecordingAPI receives props that comes from redux only while initializing - in constructor. You can fix your component by adding componentWillReceiveProps method

class RecordingAPI extends React.Component {
    constructor(props) {
        super(props);
        ...
        this.state = {
            word : this.props.word,
            state: this.props
        };
    }
    // new method that listens to props
    componentWillReceiveProps (props) {
        this.setState({
            word:   this.props.word,
            state:  this.props
        });
    }

    checkState(e){
        e.persist();
        e.preventDefault();
        e.stopPropagation();
        console.dir(this.state.word)
        console.dir(this.state.state)
    }

    render() {
        ...

        return (
            <div>
                <button onClick={(e) => this.checkState(e)}>  CheckState </button> 
            </div>
        );
    }
}

这篇关于Redux.js - 我无法使用 React Redux 映射StateToProps - 我的 React 组件块在商店初始状态上并且在 store.state 更新时无法更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆