对于使用什么而言似乎有些混淆:
<Link to='/some/path'><Redirect to='/some/path'/>history.push('/some/path')我一直在使用React/Router一段时间,不同的帖子/答案说明何时使用这些,有时它们与其他人说的不一致.所以我想我需要澄清一下.
Link和本文档:为您的应用程序提供声明性,可访问的导航.
Redirect和本文档:将导航到新位置.新位置将覆盖历史堆栈中的当前位置,如服务器端重定向(HTTP 3xx).
看起来我读过的所有帖子几乎每个人都Redirect用来浏览应用程序,没有人建议Link在这篇文章中使用.
现在history可以做同样的事情Link,Redirect除了我有一个历史堆栈跟踪.
问题1:我什么时候想使用Linkvs Redirect,另一个用例是什么?
问题2:既然history可以使用历史堆栈的额外奖励将用户路由到应用程序中的另一个位置,我应该在路由时始终只使用历史对象吗?
问题3:如果我想在应用程序之外进行路由,那么最好的方法是什么?锚标签,Window.location.href,Redirect,Link,以上都没有?
这可能是一个天真的问题,但我是新的反应 - redux,我正在学习,因为我去.
上下文:鉴于我有一个react-redux应用程序.在我的顶级组件中,我在底部有这个:
function mapStateToProps({ auth }) {
return { auth };
}
export default connect(mapStateToProps)(newComponent);
Run Code Online (Sandbox Code Playgroud)
'auth'部分来自我的reducer index.js文件:
import { combineReducers } from "redux";
import authReducer from "./authReducer";
export default combineReducers({
auth: authReducer
});
Run Code Online (Sandbox Code Playgroud)
所以现在这个组件可以访问auth附带的所有数据,在我的应用程序中包含所需的所有用户信息.
随着我的应用程序变得越来越大,我意识到我需要来自顶级组件1或2层的其他组件中的authReducer数据
我的问题是:将顶级组件与auth reducer连接起来是否更好,并将必要的信息传递给子组件?如果一个孩子100层向下需要来自authReducer的信息,我们仍然会逐层传递它吗?
或者我们只是像上面那样将authReducer连接到需要它的每个组件?反复做这件事会贵吗?
我开始在我的应用程序中使用 React 钩子,但似乎有一个又一个障碍需要弄清楚。我不确定这是因为学习曲线还是依赖项不准备使用这个新实现。任何状况之下..
在使用钩子之前,我们使用 HOC 连接到特定 API,无论是 Redux、React-Router 等。就我而言,我想访问我的 React-Router 属性(历史记录、位置)。
通常它会像文件底部一样简单:
export default withRouter(SomeComponent);
Run Code Online (Sandbox Code Playgroud)
但是现在有了钩子,我不确定如何访问这些数据。
我如何使用新的 React 钩子从 react-router 访问相同类型的数据?
这里是我user和product架构:
const productSchema = new Schema({
//...
addedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "users"
}
});
const userSchema = new Schema({
//...
addedItems: [{
type: mongoose.Schema.ObjectId,
ref: "products"
}]
});
mongoose.model("products", productSchema);
mongoose.model("users", userSchema);
Run Code Online (Sandbox Code Playgroud)
在我的节点后端路线我做这个查询:
User.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { addedItems: newProduct._id } },
{ upsert: true, new: true },
function(err, doc) {
console.log(err, doc);
}
);
Run Code Online (Sandbox Code Playgroud)
在console.log打印出这样的:
{
//...
addedItems: [ 5ab0223118599214f4dd7803 ]
}
Run Code Online (Sandbox Code Playgroud)
一切看起来都不错。我实际上是使用前端网站来查看我的mongo数据库的数据;我使用mlab.com,这是什么节目:
{
//...
"addedItems": [ …Run Code Online (Sandbox Code Playgroud) 我正在尝试更改默认淡入和淡出过渡的速度,但文档似乎没有提到如何这样做:
<Transition
items={show}
from={{ opacity: 0 }}
enter={{ opacity: 1 }}
leave={{ opacity: 0 }}>
{show => show && (props => <div style={props}>??</div>)}
</Transition>
Run Code Online (Sandbox Code Playgroud)
鉴于此代码,我将如何使淡入/淡出动画更快或更慢?
我尝试这样做(如下),但最终完全破坏了过渡。动画不再起作用:
from={{ opacity: 1, transitionDelay: "5000ms" }}
enter={{ opacity: 1, transitionDelay: "5000ms" }}
leave={{ opacity: 0, transitionDelay: "5000ms" }}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
在我渲染所有路由的 App.js 文件中,我有以下代码:
import LiveMatch from "../containers/LiveMatch";
const routes = [
//removed other routes for simplicity of post
{
path: "/livematch/:matchid", <--- here is the param I want
exact: true,
component: () => <LiveMatch />
}
];
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<div>
{routes.map((route, index) =>
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.component}
/>
)}
</div>
</BrowserRouter>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我已经设置了组件,我尝试打印出 :matchid 参数,但我一直得到一个空对象。
class LiveMatch extends Component {
constructor(props) {
super(props)
this.state = {...}
console.log(this.props) …Run Code Online (Sandbox Code Playgroud) 所以我知道如何找到两个列表的交集:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)
但是找到交叉点中未包含的所有元素的最佳方法是什么.我最初的想法是创建两个列表的联合,然后从联合中删除交集中的所有元素,如下所示:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> intersection = list(set(a) & set(b))
>>> union = list(set(a) | set(b))
>>> non_intersection = intersection - union
[2, 4, 6]
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?还是有另一种方式?
我有这个架构:
const guestSchema = new Schema({
id: String,
cart: [
{
product: {
type: mongoose.Schema.ObjectId,
ref: "products"
},
quantity: Number
}
]
});
Run Code Online (Sandbox Code Playgroud)
我有这个查询:
Guest.findOneAndUpdate(
{ id: req.sessionID },
{
$cond: [
{ "cart.product": { $ne: req.body.itemID } },
{ $push: { "cart": { product: req.body.itemID, quantity: 1 } } },
{ $inc: { "cart.quantity": 1 } }
]
},
{ upsert: true, new: true }
).exec(function(err, docs) {
err ? console.log(err) : res.send(docs);
});
Run Code Online (Sandbox Code Playgroud)
基本上,我想做的是根据条件进行更新。我尝试使用$cond,但发现该运算符没有像我正在使用的那样用于查询。
基于此:
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试设置一个测试文件以在我的应用程序上呈现路由/页面。我正在尝试使用 Redux 和 Router 包装所有内容,这就是我所拥有的:
import React from 'react';
import { render } from 'react-testing-library';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from '../../store/reducer';
import {Link, Route, Router, Switch} from 'react-router-dom'
import {createMemoryHistory} from 'history'
import ViewNode from '../Pages/ViewNode';
const customRender = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] }),
initialState,
store = createStore(reducer, initialState),
...options
} = {}
) => ({
...render(
<Provider store={store}>
<Router history={history}>{ui}</Router>
</Provider>,
options …Run Code Online (Sandbox Code Playgroud) 在搜索字典中的元素时,我在使用"in"与"get"之间有点困惑.
根据这个时间复杂度表,这里:当使用"in"时我们得到O(n)vs"get"得到O(1).
在下面的这两个代码片段中,它们实现了相同的功能,但显然使用get会更快?
#Recall that for "get" the second parameter is returned if key is not found
#O(1) time complexity
if dict.get(key, False):
return "found item"
#O(n) time complexity
if key in dict:
return "found item"
Run Code Online (Sandbox Code Playgroud)
我不明白使用get会如何改变时间复杂度,因为它们可以实现相同的目标.除了get调用实际上会返回值,如果找到它.
问题:它是如何"中的"时间复杂度为O(n),而"得"只有O(1),当他们都获得同样的结果?如果这是真的,是否有理由在词典中使用"in"?
处理promises的错误让我有点问题.所以最初我的功能设置如此,一切正常,没问题.
原版的:
const request = require("request-promise");
async () => {
const URL_HIDDEN = "...";
let info = await request(URL_HIDDEN);
info = JSON.parse(info).response.players[0];
let playtime = await request(URL_HIDDEN);
playtime = JSON.parse(playtime).response.games;
console.log(info);
console.log(playtime);
}
Run Code Online (Sandbox Code Playgroud)
这是一个缩短版本,但基本上我只是从Steam API请求信息.两个变量都打印出来,所有数据都没有问题,但是一旦我在下面的重构中做了改变.
重构:
const middleware = require("../middleware");
async () => {
const URL_HIDDEN = "...";
let requests = middleware.requestURI(URL_HIDDEN);
console.log(requests);
}
Run Code Online (Sandbox Code Playgroud)
我开始在单独的文件中的单独函数中处理所有请求.
const request = require("request-promise");
middlewareObj.requestURI = async (URL_HIDDEN) => {
console.log("1");
let info = await request(URL_HIDDEN);
info = JSON.parse(info).response.players[0];
console.log("2");
let playtime = await request(URL_HIDDEN); …Run Code Online (Sandbox Code Playgroud) 所以我有这个递归函数,它将两个数相乘,足够简单.
def mul(n: Int, m: Int):Int =
if(m > 1) n + mul(n, dec(m))
else n
Run Code Online (Sandbox Code Playgroud)
现在我试图把它变成一个尾递归函数,我试过这个:
def mulWithTail(n: Int, m: Int):Int = {
@tailrec
def iter(result: Int, x: Int):Int =
if(x == 0) result
else result + iter(result, dec(x))
iter(n, m)
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
错误:无法优化@tailrec带注释的方法iter:它包含一个不在尾部位置的递归调用
else结果+ iter(结果,dec(x))
问题:你能解释一下为什么会出现这种错误吗?我该如何重构我的代码?
我正在尝试编写一个函数来计算类型为T的元素数组中的元素数量,这些元素通过了T => Boolean类型的测试.
到目前为止我所拥有的是:
def countPass[T](elem: Array[T]) = {
var count = 0
for(x <- elem)
x match {
case x: T => count += 1
}
count
}
//TEST
println(countPass[Boolean](Array(true, 52, "test")))
Run Code Online (Sandbox Code Playgroud)
我遇到了一些错误,第一个是:
combinators.scala:45: warning: abstract type pattern T is unchecked since
it is eliminated by erasure
case x: T => count += 1
^
Run Code Online (Sandbox Code Playgroud)
下一个错误是:
combinators.scala:54: error: type mismatch;
found : Int(52)
required: Boolean
println(countPass[Boolean](Array(true, 52, "test")))
^
combinators.scala:54: error: type mismatch;
found : String("test")
required: Boolean
println(countPass[Boolean](Array(true, …Run Code Online (Sandbox Code Playgroud) reactjs ×6
react-router ×4
javascript ×3
mongodb ×2
mongoose ×2
node.js ×2
python ×2
react-redux ×2
scala ×2
animation ×1
arrays ×1
async-await ×1
css ×1
database ×1
dictionary ×1
ecmascript-6 ×1
generics ×1
hash ×1
promise ×1
python-3.x ×1
react-spring ×1
recursion ×1
redux ×1