redux reducer 不更新 store 中的状态
Posted
技术标签:
【中文标题】redux reducer 不更新 store 中的状态【英文标题】:redux reducer not updating state in store 【发布时间】:2020-10-21 02:38:51 【问题描述】:我对 redux 很陌生,所以我没有足够的知识。我正在做一个项目,在该项目中我需要设置 redux 存储并使用存储中的状态。但是当我通过减速器更新状态时..代码失败..它不会抛出任何错误,但是当我控制台时。 log(store.getState().Key) 值未更新。 我将所有文件附在下面...请帮帮我。谢谢
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import Provider from 'react-redux';
import createStore,applyMiddleware from 'redux';
import Reducers from './redux/reducers.js'
import thunk from 'redux-thunk'
export const store=createStore(Reducers,applyMiddleware(thunk));
ReactDOM.render( <Provider store=store><App /></Provider> ,document.getElementById('root'));
App.js
import React from 'react';
import Searchbar from './searchbar.js'
import connect from 'react-redux'
class App extends React.Component
render()
return (
<div>
<Searchbar ...this.props/>
</div>
);
function mapStateToProps(state)
return
state:state
export default connect(mapStateToProps)(App)
searchbar.js
import React from 'react'
import onSubmit,handleChange from '../redux/action.js'
export class Searchbar extends React.Component
render()
//console.log("2",this.props);
return (
<div className="container">
<div className="row">
<div className="col s6 offset-s3">
<form action="" onSubmit=(e)=>this.props.dispatch(onSubmit(e))>
<div className="input-field">
<input placeholder="Search" type="text" onChange=(e)=>this.props.dispatch(handleChange(e)) required/>
</div>
</form>
</div>
</div>
</div>
);
reduces.js
import state_data from './store.js'
const Reducers= function reducer(state=state_data,action)
console.log(action.type);
switch(action.type)
case "updatedata": return Object.assign(,state,movies:action.data);
case "updatekey": return Object.assign(,state,Key:action.key);
default: return state;
export default Reducers;
action.js
import store from '../index.js'
export function onSubmit(e)
e.preventDefault();
// console.log(store.getState());
return dispatch=>
return fetch(`https://api.themoviedb.org/3/search/movie?api_key=403215d4d68a271d4c5dc907db08554e&query=$store.getState().Key`)
.then(data=>data.json())
.then(data=>
console.log("fetched",data);
return
type:"updatedata",
data
);
export function handleChange(e)
return dispatch=>
console.log(e.target.value);
console.log("store",store.getState().Key);
return
type:"updatekey",
key:e.target.value
store.js
export const state_data=
movies:[],
Key:'spider'
;
【问题讨论】:
在你的 reduce.js 中 console.log(action);打印? 【参考方案1】:你需要将你的组件连接到 redux ,你可以使用 react-redux 包
在searchbar.js
中导入这个
import connect from 'react-redux';
并创建一个mapDispatchToProps
函数
const mapDispatchToProps=(dispatch)=>(
onSubmit:(e)=>dispatch(onSubmit(e))
)
像这样使用连接导出你的类组件
export default connect(undefined,mapDispatchToProps)(searchbar);
最后在表单中调用这个动作时这样做
onSubmit=(e)=>this.props.onSubmit(e)
【讨论】:
但我使用 onSubmit=(e)=>this.props.dispatch(onSubmit(e)) 直接使用 dispatch 是不对的以上是关于redux reducer 不更新 store 中的状态的主要内容,如果未能解决你的问题,请参考以下文章