gpt4 book ai didi

javascript - Redux + React-router 组件不渲染

转载 作者:行者123 更新时间:2023-11-29 21:42:01 26 4
gpt4 key购买 nike

所以我正在尝试使用 Redux 配置 React-router 我用过 this example设置基本应用程序。

当我尝试渲染我的组件时,我收到 1 个错误和 2 个警告。

错误是:Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

警告 #1:警告:React.createElement:类型不应为空或未定义。它应该是一个字符串(对于 DOM 元素)或一个 ReactClass(对于复合组件)。

警告 #2:警告:只有函数或字符串可以作为 React 组件挂载。

我只有两个简单的组件。一个 Root 组件和一个 Container 组件来测试是否一切正常。

根组件的内容:

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createHistory } from 'history';
import { createStore, combineReducers } from 'redux';
import { Router, Route } from 'react-router';
import timeline from '../reducers/timeline';

import Container from '../components/Container';

const store = createStore(combineReducers({timeline}));

store.subscribe(() => {
console.info(store.getState());
})

const history = createHistory();

React.render(
<Provider store={store}>
{() =>
<Router history={history}>
<Route path="/" component={Container}/>
</Router>
}
</Provider>,
document.getElementById('root')
);

容器组件的内容:

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Container extends Component {
render() {
return (
<div id="outter">
Container
</div>
);
}
}

function mapStateToProps(state) {
console.log(state);

return {
test: state,
};
}

export default connect(
mapStateToProps,
{
type: 'TEST_ACTION',
}
)(Container);

以防万一 - reducer 的内容也是如此:

const initialState = [
{id: 1, message: 'Test message'},
];

export default function timeline(state = initialState, action = {}) {
switch (action.type) {
case 'TEST_ACTION':
return initialState;
default:
return state;
}
}

最佳答案

我看到的一个问题是您传递给 Container 组件中的 connect 函数的第二个参数。您正在传递一个对象。根据the documentation ,如果你传递一个对象,它会期望该对象的属性是 Action 创建者(它们是函数)。所以它可能看起来像这样:

export default connect(
mapStateToProps,
{
test: () => { type: 'TEST_ACTION' }
}
)(Container);

这将向您的 props 添加一个名为 test 的属性,这将是一个您可以调用以分派(dispatch)测试操作的函数。

关于javascript - Redux + React-router 组件不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com