简体   繁体   English

同时更新本地状态和redux存储值?

[英]Update local state as well as redux store value simultaneously?

I'm making a react-redux app and I want to update localState as well as redux state values. 我正在制作一个react-redux应用程序,我想更新localState以及redux状态值。 Actually when I console.log it updates action but it can't update the state values. 实际上,当我console.log它会更新操作,但无法更新状态值。 I'm pushing my local props to firebase and it also worked but it doesn't update my redux props..... 我将我的本地道具推到了火力基地,它也起作用了,但是它没有更新我的redux道具.....

My code for actions: 我的动作代码:

export const addName = action => {
  return{
    type:'ADD_ENTRY',
    ...action
  };
};

Code for the Reducers: 减速器代码:

export const AddReducer = (state = [], action) =>{

  switch (action.type) {
    case 'ADD_ENTRY':
      return [
        ...state,
        {
          firstName:action.firstName,
          passWord:action.passWord
        }
      ]
    default:
      return state;
  }
};

App.js presentational and input field value component: App.js表示和输入字段值组件:

import React,{Component} from "react";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import * as action from './action';
let firebase = require('firebase')
var config = {
    apiKey: "my_hidden_API_key",
    authDomain: "myauthdomain.firebaseapp.com",
    databaseURL: "https://myauthdomain.firebaseio.com",
    projectId: "myApp",
    storageBucket: "myApp.appspot.com",
    messagingSenderId: "382483"
  };
  firebase.initializeApp(config);
class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      uname: '',
      pass: ''
    };
  }
  inputData = event => {
    this.setState({
      [event.target.name]:event.target.value
    });
  }
  submitData = event => {
    event.preventDefault();
    firebase
     .database()
     .ref('Entry/'+this.state.uname)
     .set({
       uname:this.state.uname,
       pass:this.state.pass
     });
     this.props.action.addName({
       userName:this.state.uname,
       passWord:this.state.pass
     });
  }
  render(){
    return(
      <div>
        <form onSubmit={this.submitData}>
          UserName:
          <input type="text" name="uname" onChange={this.inputData}/>
          Password:
          <input type="text" name="pass" onChange={this.inputData}/>
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}
function mapStateToProps(state){
  return {
    userName : state.userName,
    passWord : state.passWord
  };
};
function mapDispatchToProps(dispatch) {
  return{
    action: bindActionCreators(action,dispatch)
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App)

My Final index.js: 我的最终index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from "react-redux";
import {AddReducer} from './reducers/name';
import {createStore} from "redux";
import registerServiceWorker from './registerServiceWorker';
let store = createStore(AddReducer)
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root'));
registerServiceWorker();

Following could help you, try it as I didnt setup project to compile this: 以下内容可以为您提供帮助,请尝试一下,因为我没有设置项目来进行编译:

// cut for brevity
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uname: props.userName || '',
            pass: props.passWord || ''
        };
    }
    inputData = event => {
        this.setState({
            [event.target.name]: event.target.value
        });
    }
    submitData = event => {
        event.preventDefault();
        const { action } = this.props;
        const { uname, pass } = this.state;
        firebase
            .database()
            .ref('Entry/' + uname)
            .set({
                uname: uname,
                pass: pass
            }, error => {
                if(!error) {
                    // OK - dispatch action
                    action.addName({
                        userName: uname,
                        passWord: pass
                    });
                } else {
                    // TODO: handle failure
                }
            });
    }
    // cut for brevity
}
function mapStateToProps = (state, props) => ({
        userName: state.userName,
        passWord: state.passWord
});
// cut for brevity
export default connect(mapStateToProps, mapDispatchToProps)(App);

Also seems that your reducer is not updating store correctly 还似乎您的减速器未正确更新存储

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

  switch (action.type) {
    case 'ADD_ENTRY':
      return {
        ...state,
          userName:action.userName,
          passWord:action.passWord
        }
    default:
      return state;
  }
};

First of all, treat redux as your source of truth of your data in your application. 首先,将redux视为应用程序中数据真实性的来源。
So instead of fetching some data from localstorage , do so from the redux store. 因此, localstoragelocalstorage存储中获取一些数据, localstorage从redux存储中获取数据。
By doing the localstorage thing, you are defeating the purpose of redux. 通过执行localstorage ,您将localstorage达到redux的目的。

Secondly, if you need to keep track of a user state, like a user preference, localstorage is recommended storage to save it. 其次,如果您需要跟踪用户状态(例如用户首选项),建议使用localstorage存储来保存它。
In a React-Redux app these actions where you need to use special libraries to take action on side effects. 在React-Redux应用程序中,这些操作需要使用特殊的库来对副作用进行操作。 The two most notable ones are redux-saga and redux-thunk . 最著名的两个是redux-sagaredux-thunk
I do recommend redux-saga as it makes your app more functional and helps you avoid callback hell. 我建议您使用redux-saga因为它可以使您的应用程序更具功能性,并有助于避免回调地狱。 Also, using redux-thunk defeats the philosophy of reducer, which should be sole functions without any side-effects. 同样,使用redux-thunk会破坏reducer的理念,reduceer应该是唯一的功能,没有任何副作用。

So to post to firebase, dispatch an action on your component, which redux-saga takes it, then calls an ajax function. 因此,要发布到Firebase,在组件上调度一个动作, redux-saga会接受该动作,然后调用ajax函数。 (I can give you code samples if you want but here I'm talking about theories on how you should do it in a react-redux app). (如果需要,我可以给您代码示例,但在这里我谈论的是有关如何在react-redux应用程序中进行操作的理论)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM