Redux.js-我无法使用React映射StateToProps Redux-我的React Component块在商店初始状态,并且在store.state更新时无法更新

时间:2018-06-27 17:12:34

标签: javascript reactjs redux

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

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

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

希望这将有助于找出问题所在。

摘要:

我的问题基本上是关于mapStateToProps的,是关于将组件链接到状态存储的,AFAIK其余的工作都很好,但是 React的this.props似乎有些捷径组件,因为我使用connect()或删除了mapStateToProps方法,所以我的组件stil显示初始状态..!

Redux像最终级别的老板一样抵抗我...


游戏状态

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

提示:

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

这是我的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

这是我的container.js:

const mapStateToProps = (state) => {

  return { word: state.entry.word }
}

const mapDispatchToProps = {
     postFile: postFileAction  
}

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

我的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
      })
    });


}

在我的store.initialState中:

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

UPDATE_STATE_POSTWORD由另一个React组件提供,因此在该bug组件通过更新的单词条目触发其自身动作之前将其分派到商店。 这是我的UPDATE_STATE_POSTWORD操作片段:

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

/// reducers.js部分///

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

    }
}

谢谢

2 个答案:

答案 0 :(得分:0)

如果您使用的是react-thunk,则您的操作fn将收到dispatch,并且getState用作参数。 运行getState将为您提供应用程序的实际状态。所需的数据将传递到减速器等。

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

来修复组件。
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>
        );
    }
}

答案 1 :(得分:-1)

我当前的解决方法是直接在我的React Component中导入商店,然后按其订阅更改:

import {store} from "../App" 

    store.subscribe(() => {
      // When state will be updated
      // we will update local component state and force component to rerender 
      // with new data.

      this.setState({
        word: store.getState().entry.word // new entry.words at each update in the statge of the React.Component
      });
    });

答案:

将store.state值分配给组件的状态构造函数时,组件无法更新状态。因此,在对Component.state.property进行任何分配之外,使用this.props来引用store.state的方式就像一个charm *。 陷阱是,仅当使用React.js时,才能在道具的props.constructor.state中存储道具,但是该机制不适用于React-Redux,因此必须将道具保留在{中的任何分配之外{1}}